SlideShare a Scribd company logo
1 of 19
Download to read offline
INTRODUCTION AUX
MACROS
!

@ahoy_Jon
Jonathan Winandy 	

!

‘BI Platform Engineer at Viadeo'
LES MACROS ET MOI
2012 : [ScalaDays London] “S’il n’y a rien de nouveau
dans Scala, je vais finir par faire du Clojure …” ->
MaKro




2013 : “Atelier : Dans S’cas là”, utilisation des macros
pour augmenter les tests unitaires.	

!

2014 : Type providers ? So 2008	

!
QU’EST CE QU’UNE MACRO ?

• Une

macro est une “méthode” définie par l’utilisateur qui est
appelée lors de la compilation.	


• En

Scala on a les def macro.
UN EXEMPLE
!
!
def assert(cond: Boolean, msg: Any) = macro Asserts.assertImpl	
!
object Asserts {	
def assertImpl(c)(...,...) : ... = ????	
}	
!
// ----------------- 	
!
! assert(x < 10, "limit exceeded”)
!
!

assertImpl(c)(<[ x < 10 ]>, <[ “limit exceeded” ]>)
CLOJURE - DEMO !
(defn ifp [pred thenf elsef]	
"if in point fix style (= ((ifp even? inc dec) 2) 3)"	
(fn [a] (if (pred a) (thenf a) (elsef a))))	
	
(defn reverse-at [n col]	
"(= (reverse-at 2 [1 2 3]) [2 1 3])"	
(let [[part1 part2] (split-at n col)]	
(concat (reverse part1) part2)))	

!
(defmacro infix [form]	
(clojure.walk/postwalk (ifp seq? (partial reverse-at 2) identity) form))	

!
;; (1 + 2) est une forme infix, normalement en Clojure on écrit :	
;; (+ 1 2)	
(def e (quote (infix ((+ partial 1) map [(1 + (2 * 3)) (2 - 3)]))))	

!
(eval e) 	
;=> (8 0) ; List(8,0)	
(macroexpand e) 	
;=> (map (partial + 1) [(+ 1 (* 2 3)) (- 2 3)])	
;; c’est “l’AST” qui va être exécuté après l’expansion des macros
!
!
Expr(	
Block(	
List(	
ValDef(	
Modifiers()	
, newTermName("a")	
, TypeTree()	
, Literal(Constant(2))	
)	
, ValDef(	
Modifiers()	
, newTermName("b")	
, TypeTree()	
, Literal(Constant(3))	
)	
)	
, Apply(	
Select(Ident(newTermName("a"))	
, newTermName("$plus"))	
, List(Ident(newTermName("b"))))	
)	
)	

L’AST SCALA

{	
val a = 2	
val b = 3	
a + b	
}
UN PEU PLUS INTERACTIF
!
!
On peut inspecter les expressions dans une session de REPL avec les
commandes suivantes : 	
!
> import scala.reflect.runtime.{universe => u}	
!
> u.showRaw( u.reify {{ val a = 2 ; val b = 3 ; a+b }})

!
(showRaw ne suffit pas parfois	
!
scalac -Xplugin macro-paradise_2.10.2-2.0.0-SNAPSHOT.jar deprecation -Xprint:parser -Ystop-after:parser -Yshow-trees-compact
*.scala	
!
)	
!
UTILISATION DANS LA
NATURE
• Wartremover	

• Datomisca	

• Expecty	

• Async	

• MacWire
WARTREMOVER
!
safe {	
def x[A](a: A) = a	
// x(100)	
x(())	

!
100	
}	

!
safe {	
// Won't compile: null is disabled	
val s: String = null	
}	

!
safe {	
// Won't compile: var is disabled	
var x = 100	
}
DATOMISCA
val queryFindActorsInTitle = Query("""	
[	
:find ?name	
:in $ ?title	
:where	
[?movie :movie/title
?title]	
[?actor :actor/acts-in ?movie]	
[?actor :actor/name
?name]	
]	
""")
!
case class Person(name: String = "Fred", age: Int = 42) {	
def say(words: String*) = words.mkString(" ")	
}	

!
val person = Person()	
val expect = new Expecty()	
// Failing expectation	

!
val word1 = "ping"	
val word2 = "pong"	

!
expect {	
person.say(word1, word2) == "pong pong"	
}	

!
/*	
Output:	

!
java.lang.AssertionError:	

!
person.say(word1, word2) == "pong pong"	
|
|
|
|
|	
|
|
ping
pong
false	
|
ping pong	
Person(Fred,42)	
*/	

EXPECTY
ASYNC
def combined: Future[Int] = async {	
val future1 = slowCalcFuture	
val future2 = slowCalcFuture	
await(future1) + await(future2)	
}

def combined: Future[Int] = for {	
r1 <- future1	
r2 <- future2	
} yield r1 + r2
MACWIRE
class DatabaseAccess()	
class SecurityFilter()	
class UserFinder(databaseAccess: DatabaseAccess, 	
securityFilter: SecurityFilter)	
class UserStatusReader(userFinder: UserFinder)	
!
trait UserModule {	
import com.softwaremill.macwire.MacwireMacros._	
!
lazy val theDatabaseAccess
= wire[DatabaseAccess]	
lazy val theSecurityFilter
= wire[SecurityFilter]	
lazy val theUserFinder
= wire[UserFinder]	
lazy val theUserStatusReader = wire[UserStatusReader]	
}
DEMO MACRO
import language.experimental.macros	
!
import reflect.macros.Context	
!
!
case class Query(s:String)	
!
object TreeCleaner {	
def query(s:String):Query = macro queryValidationImpl	
!
def queryValidationImpl(c:Context)(s:c.Expr[String]) = {	
import c.universe._	
val Literal(Constant(s_query: String)) = s.tree	
println(showRaw(s))	
println(s_query)	
reify (	
new Query(s.splice)	
)	
}

https://github.com/ahoy-jon/demoMacro
UN PEU PLUS AVANCÉ …
QUASIQUOTING

(MACROPARADISE OU SCALA 2.11)

https://github.com/squito/learn_macros
sbt/sbt "project macrotests" console
import
import
import
import
import

language.experimental.macros	
reflect.macros.Context	
scala.annotation.StaticAnnotation	
scala.reflect.runtime.{universe => ru}	
ru._


val e = q"def x = 4”	
e: reflect.runtime.universe.DefDef = def x = 4	


val q"def $m = $v" = e	
m: reflect.runtime.universe.Name = x	
v: reflect.runtime.universe.Tree = 4
import scala.annotation.StaticAnnotation	
import scala.language.experimental.macros	
import scala.reflect.macros.Context	
	
class body(tree: Any) extends StaticAnnotation	
	
object Macros {	
def makeInstance = macro makeInstance_impl	

!

def makeInstance_impl(c: Context) = c.universe.reify[Any] {	
class Workaround {	
def z: Int = 13	
@body(42) def v: Int = macro Macros.selectField_impl	
}	
new Workaround {}	
}	
def selectField_impl(c: Context) = c.Expr(	
c.macroApplication.symbol.annotations.filter(	
_.tpe <:< c.typeOf[body]	
).head.scalaArgs.head	
) 	

FAKE
TYPE
PROVIDER

}	

!

val myInstance = Macros.makeInstance	
myInstance: AnyRef{def z: Int; def v: Int} = $anon$1@35d39d01	

!

myInstance.z	
res7: Int = 13	

!

myInstance.v	
res8: Int = 42	

!

http://meta.plasm.us/posts/2013/07/12/vampire-methods-for-structural-types/

More Related Content

What's hot

No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldtcurdt
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212Mahmoud Samir Fayed
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streamsmattpodwysocki
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APItvaleev
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine Aleksandar Prokopec
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsAndrei Pangin
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersSaeid Zebardast
 
Predictably
PredictablyPredictably
Predictablyztellman
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJason Swartz
 

What's hot (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
No dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real worldNo dark magic - Byte code engineering in the real world
No dark magic - Byte code engineering in the real world
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Exception Handling in Scala
Exception Handling in ScalaException Handling in Scala
Exception Handling in Scala
 
JPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream APIJPoint 2016 - Валеев Тагир - Странности Stream API
JPoint 2016 - Валеев Тагир - Странности Stream API
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine ScalaDays 2014 - Reactive Scala 3D Game Engine
ScalaDays 2014 - Reactive Scala 3D Game Engine
 
Down to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap DumpsDown to Stack Traces, up from Heap Dumps
Down to Stack Traces, up from Heap Dumps
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
Predictably
PredictablyPredictably
Predictably
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Java 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason SwartzJava 8 - An Introduction by Jason Swartz
Java 8 - An Introduction by Jason Swartz
 
Rust ⇋ JavaScript
Rust ⇋ JavaScriptRust ⇋ JavaScript
Rust ⇋ JavaScript
 

Viewers also liked

Introduction à kafka
Introduction à kafkaIntroduction à kafka
Introduction à kafkaunivalence
 
Big data forever
Big data foreverBig data forever
Big data foreverunivalence
 
AWS Lambda: Event-driven Code in the Cloud
AWS Lambda: Event-driven Code in the CloudAWS Lambda: Event-driven Code in the Cloud
AWS Lambda: Event-driven Code in the CloudAmazon Web Services
 
Data encoding and Metadata for Streams
Data encoding and Metadata for StreamsData encoding and Metadata for Streams
Data encoding and Metadata for Streamsunivalence
 
Logging in Scala
Logging in ScalaLogging in Scala
Logging in ScalaJohn Nestor
 
Streaming in Scala with Avro
Streaming in Scala with AvroStreaming in Scala with Avro
Streaming in Scala with Avrounivalence
 
Type Checking Scala Spark Datasets: Dataset Transforms
Type Checking Scala Spark Datasets: Dataset TransformsType Checking Scala Spark Datasets: Dataset Transforms
Type Checking Scala Spark Datasets: Dataset TransformsJohn Nestor
 
Test strategies for data processing pipelines
Test strategies for data processing pipelinesTest strategies for data processing pipelines
Test strategies for data processing pipelinesLars Albertsson
 
How to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsHow to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsJulien Le Dem
 
Parquet and AVRO
Parquet and AVROParquet and AVRO
Parquet and AVROairisData
 
Parquet Strata/Hadoop World, New York 2013
Parquet Strata/Hadoop World, New York 2013Parquet Strata/Hadoop World, New York 2013
Parquet Strata/Hadoop World, New York 2013Julien Le Dem
 
File Format Benchmarks - Avro, JSON, ORC, & Parquet
File Format Benchmarks - Avro, JSON, ORC, & ParquetFile Format Benchmarks - Avro, JSON, ORC, & Parquet
File Format Benchmarks - Avro, JSON, ORC, & ParquetOwen O'Malley
 
Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Cloudera, Inc.
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineeringunivalence
 
Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...
Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...
Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...StampedeCon
 

Viewers also liked (15)

Introduction à kafka
Introduction à kafkaIntroduction à kafka
Introduction à kafka
 
Big data forever
Big data foreverBig data forever
Big data forever
 
AWS Lambda: Event-driven Code in the Cloud
AWS Lambda: Event-driven Code in the CloudAWS Lambda: Event-driven Code in the Cloud
AWS Lambda: Event-driven Code in the Cloud
 
Data encoding and Metadata for Streams
Data encoding and Metadata for StreamsData encoding and Metadata for Streams
Data encoding and Metadata for Streams
 
Logging in Scala
Logging in ScalaLogging in Scala
Logging in Scala
 
Streaming in Scala with Avro
Streaming in Scala with AvroStreaming in Scala with Avro
Streaming in Scala with Avro
 
Type Checking Scala Spark Datasets: Dataset Transforms
Type Checking Scala Spark Datasets: Dataset TransformsType Checking Scala Spark Datasets: Dataset Transforms
Type Checking Scala Spark Datasets: Dataset Transforms
 
Test strategies for data processing pipelines
Test strategies for data processing pipelinesTest strategies for data processing pipelines
Test strategies for data processing pipelines
 
How to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analyticsHow to use Parquet as a basis for ETL and analytics
How to use Parquet as a basis for ETL and analytics
 
Parquet and AVRO
Parquet and AVROParquet and AVRO
Parquet and AVRO
 
Parquet Strata/Hadoop World, New York 2013
Parquet Strata/Hadoop World, New York 2013Parquet Strata/Hadoop World, New York 2013
Parquet Strata/Hadoop World, New York 2013
 
File Format Benchmarks - Avro, JSON, ORC, & Parquet
File Format Benchmarks - Avro, JSON, ORC, & ParquetFile Format Benchmarks - Avro, JSON, ORC, & Parquet
File Format Benchmarks - Avro, JSON, ORC, & Parquet
 
Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0Efficient Data Storage for Analytics with Apache Parquet 2.0
Efficient Data Storage for Analytics with Apache Parquet 2.0
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineering
 
Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...
Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...
Choosing an HDFS data storage format- Avro vs. Parquet and more - StampedeCon...
 

Similar to Introduction aux Macros

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVMJarek Ratajski
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinDmitry Pranchuk
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Codemotion
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 

Similar to Introduction aux Macros (20)

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Beauty and the beast - Haskell on JVM
Beauty and the beast  - Haskell on JVMBeauty and the beast  - Haskell on JVM
Beauty and the beast - Haskell on JVM
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on Kotlin
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Eta
EtaEta
Eta
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 

Recently uploaded

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Recently uploaded (20)

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

Introduction aux Macros

  • 2. Jonathan Winandy ! ‘BI Platform Engineer at Viadeo'
  • 3. LES MACROS ET MOI 2012 : [ScalaDays London] “S’il n’y a rien de nouveau dans Scala, je vais finir par faire du Clojure …” -> MaKro
 
 2013 : “Atelier : Dans S’cas là”, utilisation des macros pour augmenter les tests unitaires. ! 2014 : Type providers ? So 2008 !
  • 4. QU’EST CE QU’UNE MACRO ? • Une macro est une “méthode” définie par l’utilisateur qui est appelée lors de la compilation. • En Scala on a les def macro.
  • 5. UN EXEMPLE ! ! def assert(cond: Boolean, msg: Any) = macro Asserts.assertImpl ! object Asserts { def assertImpl(c)(...,...) : ... = ???? } ! // ----------------- ! ! assert(x < 10, "limit exceeded”) ! ! assertImpl(c)(<[ x < 10 ]>, <[ “limit exceeded” ]>)
  • 6. CLOJURE - DEMO ! (defn ifp [pred thenf elsef] "if in point fix style (= ((ifp even? inc dec) 2) 3)" (fn [a] (if (pred a) (thenf a) (elsef a)))) (defn reverse-at [n col] "(= (reverse-at 2 [1 2 3]) [2 1 3])" (let [[part1 part2] (split-at n col)] (concat (reverse part1) part2))) ! (defmacro infix [form] (clojure.walk/postwalk (ifp seq? (partial reverse-at 2) identity) form)) ! ;; (1 + 2) est une forme infix, normalement en Clojure on écrit : ;; (+ 1 2) (def e (quote (infix ((+ partial 1) map [(1 + (2 * 3)) (2 - 3)])))) ! (eval e) ;=> (8 0) ; List(8,0) (macroexpand e) ;=> (map (partial + 1) [(+ 1 (* 2 3)) (- 2 3)]) ;; c’est “l’AST” qui va être exécuté après l’expansion des macros
  • 7. ! ! Expr( Block( List( ValDef( Modifiers() , newTermName("a") , TypeTree() , Literal(Constant(2)) ) , ValDef( Modifiers() , newTermName("b") , TypeTree() , Literal(Constant(3)) ) ) , Apply( Select(Ident(newTermName("a")) , newTermName("$plus")) , List(Ident(newTermName("b")))) ) ) L’AST SCALA { val a = 2 val b = 3 a + b }
  • 8. UN PEU PLUS INTERACTIF ! ! On peut inspecter les expressions dans une session de REPL avec les commandes suivantes : ! > import scala.reflect.runtime.{universe => u} ! > u.showRaw( u.reify {{ val a = 2 ; val b = 3 ; a+b }})
 ! (showRaw ne suffit pas parfois ! scalac -Xplugin macro-paradise_2.10.2-2.0.0-SNAPSHOT.jar deprecation -Xprint:parser -Ystop-after:parser -Yshow-trees-compact *.scala ! ) !
  • 9. UTILISATION DANS LA NATURE • Wartremover • Datomisca • Expecty • Async • MacWire
  • 10. WARTREMOVER ! safe { def x[A](a: A) = a // x(100) x(()) ! 100 } ! safe { // Won't compile: null is disabled val s: String = null } ! safe { // Won't compile: var is disabled var x = 100 }
  • 11. DATOMISCA val queryFindActorsInTitle = Query(""" [ :find ?name :in $ ?title :where [?movie :movie/title ?title] [?actor :actor/acts-in ?movie] [?actor :actor/name ?name] ] """)
  • 12. ! case class Person(name: String = "Fred", age: Int = 42) { def say(words: String*) = words.mkString(" ") } ! val person = Person() val expect = new Expecty() // Failing expectation ! val word1 = "ping" val word2 = "pong" ! expect { person.say(word1, word2) == "pong pong" } ! /* Output: ! java.lang.AssertionError: ! person.say(word1, word2) == "pong pong" | | | | | | | ping pong false | ping pong Person(Fred,42) */ EXPECTY
  • 13. ASYNC def combined: Future[Int] = async { val future1 = slowCalcFuture val future2 = slowCalcFuture await(future1) + await(future2) } def combined: Future[Int] = for { r1 <- future1 r2 <- future2 } yield r1 + r2
  • 14. MACWIRE class DatabaseAccess() class SecurityFilter() class UserFinder(databaseAccess: DatabaseAccess, securityFilter: SecurityFilter) class UserStatusReader(userFinder: UserFinder) ! trait UserModule { import com.softwaremill.macwire.MacwireMacros._ ! lazy val theDatabaseAccess = wire[DatabaseAccess] lazy val theSecurityFilter = wire[SecurityFilter] lazy val theUserFinder = wire[UserFinder] lazy val theUserStatusReader = wire[UserStatusReader] }
  • 16. import language.experimental.macros ! import reflect.macros.Context ! ! case class Query(s:String) ! object TreeCleaner { def query(s:String):Query = macro queryValidationImpl ! def queryValidationImpl(c:Context)(s:c.Expr[String]) = { import c.universe._ val Literal(Constant(s_query: String)) = s.tree println(showRaw(s)) println(s_query) reify ( new Query(s.splice) ) } https://github.com/ahoy-jon/demoMacro
  • 17. UN PEU PLUS AVANCÉ …
  • 18. QUASIQUOTING (MACROPARADISE OU SCALA 2.11) https://github.com/squito/learn_macros sbt/sbt "project macrotests" console import import import import import language.experimental.macros reflect.macros.Context scala.annotation.StaticAnnotation scala.reflect.runtime.{universe => ru} ru._
 val e = q"def x = 4” e: reflect.runtime.universe.DefDef = def x = 4 
 val q"def $m = $v" = e m: reflect.runtime.universe.Name = x v: reflect.runtime.universe.Tree = 4
  • 19. import scala.annotation.StaticAnnotation import scala.language.experimental.macros import scala.reflect.macros.Context class body(tree: Any) extends StaticAnnotation object Macros { def makeInstance = macro makeInstance_impl ! def makeInstance_impl(c: Context) = c.universe.reify[Any] { class Workaround { def z: Int = 13 @body(42) def v: Int = macro Macros.selectField_impl } new Workaround {} } def selectField_impl(c: Context) = c.Expr( c.macroApplication.symbol.annotations.filter( _.tpe <:< c.typeOf[body] ).head.scalaArgs.head ) FAKE TYPE PROVIDER } ! val myInstance = Macros.makeInstance myInstance: AnyRef{def z: Int; def v: Int} = $anon$1@35d39d01 ! myInstance.z res7: Int = 13 ! myInstance.v res8: Int = 42 ! http://meta.plasm.us/posts/2013/07/12/vampire-methods-for-structural-types/