SlideShare a Scribd company logo
1 of 17
Download to read offline
Scala Macros

  Eugene Burmako
Jan Christopher Vogt



  London, 2012
Scala Macros
Empower developers to
extend the compiler and stay sane!

This enables compile-time:
  – checks
  – processing
  – AST transformations
  – code generation
  – shipping of ASTs to runtime
Implementation
Compile-time metaprogramming has long
existed in Lisp, so it should be easy to
implement, right?
Trickiness
Homoiconicity for a language with syntax and
types is hard.

Being non-hygienic is evil, being hygienic
imposes a complexity tax on the spec.

Need quasiquotations to make AST
manipulations bearable. Yet another concept.
Beauty
Martin Odersky was suspicious:

“And, we'd need to be convinced that it is
beautifully simple, or it won't go into Scala”.

Here is what convinced Martin:
Cats
The essence
Scala reflection provides a slice of the compiler’s
cake. The infrastructure is already there.

Macros are (Tree*, Type*) => Tree functions.
Just as simple as that.

Hygiene itself is implemented by a macro. Hence
we stay minimalistic and flexible.
USE CASE: SLICK
SLICK overview
val coffees = Queryable[Coffee]( /* db connection */ )
coffees      .filter( c => c.id == 101 )

implemented using macros

                handed over
                to runtime
   compile time (reification)      runtime
                                                    SQL

     SLICK
                           Scala     SLICK Query
   Queryable                                       NoSQL
                           ASTs          ASTs
   frontend
                                                     Web
                                                   services


                                                              9
Macros in SLICK
val coffees = Queryable[Coffee]( /* db connection */ )
coffees      .filter( c => c.id == 101 )


    implemented as a macro that works on argument AST at compile time

def filter[T]( predicate: T => Boolean ) : Queryable[T] =
                                 macro QueryableMacros.filter[T]

object QueryableMacros{
  def filter[T:c.TypeTag] (c: scala.reflect.makro.Context)
                 (predicate : c.mirror.Expr[T => Boolean]) = …
}
A macro body
object QueryableMacros{

  // macro implementation signature
  def filter[T:c.TypeTag] (c: scala.reflect.makro.Context)
                 (predicate: c.mirror.Expr[T => Boolean]) = {

  // reify tree (ship to runtime)

  val reifiedPredicate =
      c.mirror.Expr[ reflect.mirror.Expr[T => Boolean] ](
        c.reifyTree( c.reflectMirrorPrefix, projection.tree ) )
                                                   splicing
   // splice into runtime call
  c.reify{ translate("filter", c.prefix.eval, reifiedPredicate.eval ) }
}}
                          inlined at the call site (macro expansion),
                          translates queries further at runtime, e.g. to SQL
Resulting macro expansion

coffees      .filter( c => c.id == 101 )




translate(
  "filter",
  coffees,
  Function( List("c"),                      Scala AST
      Apply( Select("c", "id"), "==", List(
        Literal(Constant(101)))))
)
                           That are macros in SLICK
Applications in the compiler
• Removed a compiler phase (LiftCode)
• Made a 80% solution (manifests) a 99%
  solution (type tags)
• Manifests à la carte – no longer hardcoded in
  Implicits.scala, it‘s just several macros (you
  can write your own implementations!)
• Ideas: SourceLocations, SourceContexts, static
  requirements on the compiler and the
  compilation environment
Applications in the wild
•   SLICK
•   Macrocosm
•   Scalatex
•   Expecty
•   Scalaxy
•   Ideas: procedure typing with arrows, lens
    generation, ACP DSL, zero-overhead mocks
Future work
•   Debugging generated code
•   Untyped macros
•   Type macros
•   Macro annotations
•   Replacing the compiler with a macro
Future work
•   Debugging generated code
•   Untyped macros
•   Type macros
•   Macro annotations
•   Replacing the compiler with a macro

Come on, just kidding about the last one!
Thank you!



Questions and answers
www.scalamacros.org

More Related Content

What's hot

Fundamentals of java --- version 2
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2
Uday Sharma
 

What's hot (20)

The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
A Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to ScalaA Brief, but Dense, Intro to Scala
A Brief, but Dense, Intro to Scala
 
Migrating Legacy Data (Ruby Midwest)
Migrating Legacy Data (Ruby Midwest)Migrating Legacy Data (Ruby Midwest)
Migrating Legacy Data (Ruby Midwest)
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Streams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to RxStreams, Streams Everywhere! An Introduction to Rx
Streams, Streams Everywhere! An Introduction to Rx
 
An Introduction to RxJava
An Introduction to RxJavaAn Introduction to RxJava
An Introduction to RxJava
 
Reenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWSReenabling SOAP using ERJaxWS
Reenabling SOAP using ERJaxWS
 
Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009Rails and Legacy Databases - RailsConf 2009
Rails and Legacy Databases - RailsConf 2009
 
Reaching the lambda heaven
Reaching the lambda heavenReaching the lambda heaven
Reaching the lambda heaven
 
Clojure & Scala
Clojure & ScalaClojure & Scala
Clojure & Scala
 
Fundamentals of java --- version 2
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
Reactive Android: RxJava and beyond
Reactive Android: RxJava and beyondReactive Android: RxJava and beyond
Reactive Android: RxJava and beyond
 
How we use Fluentd in Treasure Data
How we use Fluentd in Treasure DataHow we use Fluentd in Treasure Data
How we use Fluentd in Treasure Data
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 

Viewers also liked (11)

Nps
NpsNps
Nps
 
Arvindsujeeth scaladays12
Arvindsujeeth scaladays12Arvindsujeeth scaladays12
Arvindsujeeth scaladays12
 
Man made marvels
Man made marvelsMan made marvels
Man made marvels
 
Scala days mizushima
Scala days mizushimaScala days mizushima
Scala days mizushima
 
Prediction suretogowrong
Prediction suretogowrongPrediction suretogowrong
Prediction suretogowrong
 
Test driven infrastructure
Test driven infrastructureTest driven infrastructure
Test driven infrastructure
 
Cnc scala-presentation
Cnc scala-presentationCnc scala-presentation
Cnc scala-presentation
 
Proposal parade seni
Proposal parade seniProposal parade seni
Proposal parade seni
 
Frase dan klausa
Frase dan klausaFrase dan klausa
Frase dan klausa
 
Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012Zaharia spark-scala-days-2012
Zaharia spark-scala-days-2012
 
EDS selection & implementation @ CCC
EDS selection & implementation @ CCCEDS selection & implementation @ CCC
EDS selection & implementation @ CCC
 

Similar to Project kepler compile time metaprogramming for scala

Kafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around KafkaKafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around Kafka
Guido Schmutz
 

Similar to Project kepler compile time metaprogramming for scala (20)

Devoxx
DevoxxDevoxx
Devoxx
 
Scala active record
Scala active recordScala active record
Scala active record
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
 
Artigo 81 - spark_tutorial.pdf
Artigo 81 - spark_tutorial.pdfArtigo 81 - spark_tutorial.pdf
Artigo 81 - spark_tutorial.pdf
 
Martin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMartin Odersky: What's next for Scala
Martin Odersky: What's next for Scala
 
Building a High-Performance Database with Scala, Akka, and Spark
Building a High-Performance Database with Scala, Akka, and SparkBuilding a High-Performance Database with Scala, Akka, and Spark
Building a High-Performance Database with Scala, Akka, and Spark
 
KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!KSQL - Stream Processing simplified!
KSQL - Stream Processing simplified!
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
KSQL Deep Dive - The Open Source Streaming Engine for Apache Kafka
KSQL Deep Dive - The Open Source Streaming Engine for Apache KafkaKSQL Deep Dive - The Open Source Streaming Engine for Apache Kafka
KSQL Deep Dive - The Open Source Streaming Engine for Apache Kafka
 
Productionalizing spark streaming applications
Productionalizing spark streaming applicationsProductionalizing spark streaming applications
Productionalizing spark streaming applications
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
Event streaming webinar feb 2020
Event streaming webinar feb 2020Event streaming webinar feb 2020
Event streaming webinar feb 2020
 
Building a Real-time Streaming ETL Framework Using ksqlDB and NoSQL
Building a Real-time Streaming ETL Framework Using ksqlDB and NoSQLBuilding a Real-time Streaming ETL Framework Using ksqlDB and NoSQL
Building a Real-time Streaming ETL Framework Using ksqlDB and NoSQL
 
Kafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around KafkaKafka Connect & Streams - the ecosystem around Kafka
Kafka Connect & Streams - the ecosystem around Kafka
 
Developing distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka ClusterDeveloping distributed applications with Akka and Akka Cluster
Developing distributed applications with Akka and Akka Cluster
 

More from Skills Matter Talks

More from Skills Matter Talks (9)

Couch db skillsmatter-prognosql
Couch db skillsmatter-prognosqlCouch db skillsmatter-prognosql
Couch db skillsmatter-prognosql
 
Jordan west real workscalazfinal2
Jordan west   real workscalazfinal2Jordan west   real workscalazfinal2
Jordan west real workscalazfinal2
 
(Oleg zhurakousky)spring integration-scala-intro
(Oleg zhurakousky)spring integration-scala-intro(Oleg zhurakousky)spring integration-scala-intro
(Oleg zhurakousky)spring integration-scala-intro
 
SCALA DAYS 2012: Ben Parker on Interactivity - Anti-XML in Anger
SCALA DAYS 2012: Ben Parker on Interactivity - Anti-XML in AngerSCALA DAYS 2012: Ben Parker on Interactivity - Anti-XML in Anger
SCALA DAYS 2012: Ben Parker on Interactivity - Anti-XML in Anger
 
Real World Scalaz
Real World ScalazReal World Scalaz
Real World Scalaz
 
CukeUp! 2012: Michael Nacos on Just enough infrastructure for product develop...
CukeUp! 2012: Michael Nacos on Just enough infrastructure for product develop...CukeUp! 2012: Michael Nacos on Just enough infrastructure for product develop...
CukeUp! 2012: Michael Nacos on Just enough infrastructure for product develop...
 
Tmt predictions 2011
Tmt predictions 2011Tmt predictions 2011
Tmt predictions 2011
 
Martin sustrik future_of_messaging
Martin sustrik future_of_messagingMartin sustrik future_of_messaging
Martin sustrik future_of_messaging
 
Marek pubsubhuddle realtime_web
Marek pubsubhuddle realtime_webMarek pubsubhuddle realtime_web
Marek pubsubhuddle realtime_web
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

Project kepler compile time metaprogramming for scala

  • 1. Scala Macros Eugene Burmako Jan Christopher Vogt London, 2012
  • 2. Scala Macros Empower developers to extend the compiler and stay sane! This enables compile-time: – checks – processing – AST transformations – code generation – shipping of ASTs to runtime
  • 3. Implementation Compile-time metaprogramming has long existed in Lisp, so it should be easy to implement, right?
  • 4. Trickiness Homoiconicity for a language with syntax and types is hard. Being non-hygienic is evil, being hygienic imposes a complexity tax on the spec. Need quasiquotations to make AST manipulations bearable. Yet another concept.
  • 5. Beauty Martin Odersky was suspicious: “And, we'd need to be convinced that it is beautifully simple, or it won't go into Scala”. Here is what convinced Martin:
  • 7. The essence Scala reflection provides a slice of the compiler’s cake. The infrastructure is already there. Macros are (Tree*, Type*) => Tree functions. Just as simple as that. Hygiene itself is implemented by a macro. Hence we stay minimalistic and flexible.
  • 9. SLICK overview val coffees = Queryable[Coffee]( /* db connection */ ) coffees .filter( c => c.id == 101 ) implemented using macros handed over to runtime compile time (reification) runtime SQL SLICK Scala SLICK Query Queryable NoSQL ASTs ASTs frontend Web services 9
  • 10. Macros in SLICK val coffees = Queryable[Coffee]( /* db connection */ ) coffees .filter( c => c.id == 101 ) implemented as a macro that works on argument AST at compile time def filter[T]( predicate: T => Boolean ) : Queryable[T] = macro QueryableMacros.filter[T] object QueryableMacros{ def filter[T:c.TypeTag] (c: scala.reflect.makro.Context) (predicate : c.mirror.Expr[T => Boolean]) = … }
  • 11. A macro body object QueryableMacros{ // macro implementation signature def filter[T:c.TypeTag] (c: scala.reflect.makro.Context) (predicate: c.mirror.Expr[T => Boolean]) = { // reify tree (ship to runtime) val reifiedPredicate = c.mirror.Expr[ reflect.mirror.Expr[T => Boolean] ]( c.reifyTree( c.reflectMirrorPrefix, projection.tree ) ) splicing // splice into runtime call c.reify{ translate("filter", c.prefix.eval, reifiedPredicate.eval ) } }} inlined at the call site (macro expansion), translates queries further at runtime, e.g. to SQL
  • 12. Resulting macro expansion coffees .filter( c => c.id == 101 ) translate( "filter", coffees, Function( List("c"), Scala AST Apply( Select("c", "id"), "==", List( Literal(Constant(101))))) ) That are macros in SLICK
  • 13. Applications in the compiler • Removed a compiler phase (LiftCode) • Made a 80% solution (manifests) a 99% solution (type tags) • Manifests à la carte – no longer hardcoded in Implicits.scala, it‘s just several macros (you can write your own implementations!) • Ideas: SourceLocations, SourceContexts, static requirements on the compiler and the compilation environment
  • 14. Applications in the wild • SLICK • Macrocosm • Scalatex • Expecty • Scalaxy • Ideas: procedure typing with arrows, lens generation, ACP DSL, zero-overhead mocks
  • 15. Future work • Debugging generated code • Untyped macros • Type macros • Macro annotations • Replacing the compiler with a macro
  • 16. Future work • Debugging generated code • Untyped macros • Type macros • Macro annotations • Replacing the compiler with a macro Come on, just kidding about the last one!
  • 17. Thank you! Questions and answers www.scalamacros.org