SlideShare a Scribd company logo
1 of 17
Download to read offline
Macro in Scala
Naoki Takezoe
@takezoen
BizReach, Inc
1 Oct. 2016 #渋谷java 17th
What's Macro?
C
Expand special directive in source code
before compilation by pre-processor
#define square(x) ((x) * (x))
printf("i * i = %dn", i, square(i));
#define DEBUG
#ifdef DEBUG
printf("debug: i = %dn", i)
#endif
Lisp (also Scala or Rust)
Generate AST in compile-time
(defmacro when (test &body body)
`(if ,test (progn ,@body)))
(progn
(when (= 1 1)
(print "Hello,")
(print "World!!")))
(progn
(if (= 1 1)
(progn
(print "Hello,")
(print "World!!"))))
Expand by Macro
Example in Scala
def assert(cond: Boolean, msg: String): Unit
= macro assertImpl
def assertImpl(c: Context)
(cond: c.Expr[Boolean], msg: c.Expr[String]) = {
import c.universe._
q"if(!$cond){ throw new AssertionError($msg) }"
}
Example in Scala
assert(i == 1, "i does not 1")
if(i == 1){
throw new AssertionError("i does not 1")
}
Expand by Macro
Note: Macro have to be compiled before main compilation
Use cases
Use cases
● Validation
● Type generation
● DSL
● Optimization
without runtime overhead
Quill
● Database access library for Scala
● Do in compile-time by macro
○ Translate typesafe DSL to SQL
○ SQL validation against real database
val q = quote {
query[Person].filter(p => p.age > 18)
}
// SELECT p.id, p.name, p.age FROM Person p WHERE p.age > 18
http://getquill.io/
Macro in Scala
Macro type
● def macro
○ callable as same as normal function
● Macro annotation
○ triggered by annotation
○ requires Macro Paradise plug-in
@main object Test {
println("hello world")
}
object Test {
def main(args: Array[String]): Unit = {
println("hello world")
}
}
Expand by Macro annotation
How to construct AST?
● AST model
● reify
● Quasiquotes
AST model
def compileTimeImpl(c: Context)() = {
Literal(Constant(new java.util.Date().toString))
}
reify
def assertImpl(c: Context)
(cond: c.Expr[Boolean], msg: c.Expr[String]) = {
import c.universe._
reify(if(!cond.splice){
throw new AssertionError(msg.splice)
})
}
Quasiquotes
def assertImpl(c: Context)
(cond: c.Expr[Boolean], msg: c.Expr[String]) = {
import c.universe._
q"if(!$cond){ throw new AssertionError($msg) }"
}
Future: scala.mata
● Metaprogramming toolkit for Scala
● Replace scala.reflect
○ More simple and safe
● Scala Macro will move to scala.meta based
○ Only Macro annotation is available by Macro
Paradise plug-in currently
Let's learn Macro!

More Related Content

What's hot

Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming
Cloudflare
 
Gaucheで本を作る
Gaucheで本を作るGaucheで本を作る
Gaucheで本を作る
guest7a66b8
 

What's hot (15)

Unidad 4 robotica.docx
Unidad 4 robotica.docxUnidad 4 robotica.docx
Unidad 4 robotica.docx
 
ECMA Script
ECMA ScriptECMA Script
ECMA Script
 
Modern frontend in react.js
Modern frontend in react.jsModern frontend in react.js
Modern frontend in react.js
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFx
 
Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
 
Gaucheで本を作る
Gaucheで本を作るGaucheで本を作る
Gaucheで本を作る
 
Go memory
Go memoryGo memory
Go memory
 
Django district pip, virtualenv, virtualenv wrapper & more
Django district  pip, virtualenv, virtualenv wrapper & moreDjango district  pip, virtualenv, virtualenv wrapper & more
Django district pip, virtualenv, virtualenv wrapper & more
 
SWIFT1 Optional
SWIFT1 OptionalSWIFT1 Optional
SWIFT1 Optional
 
Python 3 - tutorial
Python 3 - tutorialPython 3 - tutorial
Python 3 - tutorial
 
Positive Hack Days. Тараканов. Мастер-класс: уязвимости нулевого дня
Positive Hack Days. Тараканов. Мастер-класс: уязвимости нулевого дняPositive Hack Days. Тараканов. Мастер-класс: уязвимости нулевого дня
Positive Hack Days. Тараканов. Мастер-класс: уязвимости нулевого дня
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 

Viewers also liked

Type-safe front-end development with Scala
Type-safe front-end development with ScalaType-safe front-end development with Scala
Type-safe front-end development with Scala
takezoe
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
takezoe
 
Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
takezoe
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in Scala
Roberto Casadei
 
8ink 기획서V1 0 김수현,유지은
8ink 기획서V1 0 김수현,유지은8ink 기획서V1 0 김수현,유지은
8ink 기획서V1 0 김수현,유지은
jin_yoo
 

Viewers also liked (20)

Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 
Type-safe front-end development with Scala
Type-safe front-end development with ScalaType-safe front-end development with Scala
Type-safe front-end development with Scala
 
Tracing Microservices with Zipkin
Tracing Microservices with ZipkinTracing Microservices with Zipkin
Tracing Microservices with Zipkin
 
Scala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.jsScala Warrior and type-safe front-end development with Scala.js
Scala Warrior and type-safe front-end development with Scala.js
 
Skinny Framework で始めた Scala
Skinny Framework で始めた ScalaSkinny Framework で始めた Scala
Skinny Framework で始めた Scala
 
WAS LibertyでCloud-ReadyなJava EE7アプリ開発
WAS LibertyでCloud-ReadyなJava EE7アプリ開発WAS LibertyでCloud-ReadyなJava EE7アプリ開発
WAS LibertyでCloud-ReadyなJava EE7アプリ開発
 
What is doobie? - database access for scala -
What is doobie? - database access for scala -What is doobie? - database access for scala -
What is doobie? - database access for scala -
 
Practical Aggregate Programming in Scala
Practical Aggregate Programming in ScalaPractical Aggregate Programming in Scala
Practical Aggregate Programming in Scala
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala story
 
Unbound/NSD最新情報(OSC 2014 Tokyo/Spring)
Unbound/NSD最新情報(OSC 2014 Tokyo/Spring)Unbound/NSD最新情報(OSC 2014 Tokyo/Spring)
Unbound/NSD最新情報(OSC 2014 Tokyo/Spring)
 
実戦Scala
実戦Scala実戦Scala
実戦Scala
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and counting
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Skinny Meetup Tokyo 2 日本語スライド
Skinny Meetup Tokyo 2 日本語スライドSkinny Meetup Tokyo 2 日本語スライド
Skinny Meetup Tokyo 2 日本語スライド
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
Reactive database access with Slick3
Reactive database access with Slick3Reactive database access with Slick3
Reactive database access with Slick3
 
Skinny 2 Update
Skinny 2 UpdateSkinny 2 Update
Skinny 2 Update
 
Presentación final
Presentación finalPresentación final
Presentación final
 
FAQ How do I find My Ideal Virtual Assistant
FAQ How do I find My Ideal Virtual AssistantFAQ How do I find My Ideal Virtual Assistant
FAQ How do I find My Ideal Virtual Assistant
 
8ink 기획서V1 0 김수현,유지은
8ink 기획서V1 0 김수현,유지은8ink 기획서V1 0 김수현,유지은
8ink 기획서V1 0 김수현,유지은
 

Similar to Macro in Scala

Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
Jan Kronquist
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
univalence
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Similar to Macro in Scala (20)

Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Introduction aux Macros
Introduction aux MacrosIntroduction aux Macros
Introduction aux Macros
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
LISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола МозговийLISP: назад в будущее, Микола Мозговий
LISP: назад в будущее, Микола Мозговий
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8JavaScript Editions ES7, ES8 and ES9 vs V8
JavaScript Editions ES7, ES8 and ES9 vs V8
 
Spark devoxx2014
Spark devoxx2014Spark devoxx2014
Spark devoxx2014
 
Javantura v3 - ES6 – Future Is Now – Nenad Pečanac
Javantura v3 - ES6 – Future Is Now – Nenad PečanacJavantura v3 - ES6 – Future Is Now – Nenad Pečanac
Javantura v3 - ES6 – Future Is Now – Nenad Pečanac
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Introducing Kogito
Introducing KogitoIntroducing Kogito
Introducing Kogito
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
ES6 - JavaCro 2016
ES6 - JavaCro 2016ES6 - JavaCro 2016
ES6 - JavaCro 2016
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Javascript status 2016
Javascript status 2016Javascript status 2016
Javascript status 2016
 

More from takezoe

Journey of Migrating Millions of Queries on The Cloud
Journey of Migrating Millions of Queries on The CloudJourney of Migrating Millions of Queries on The Cloud
Journey of Migrating Millions of Queries on The Cloud
takezoe
 
GitBucket: Git Centric Software Development Platform by Scala
GitBucket:  Git Centric Software Development Platform by ScalaGitBucket:  Git Centric Software Development Platform by Scala
GitBucket: Git Centric Software Development Platform by Scala
takezoe
 
Scala製機械学習サーバ「Apache PredictionIO」
Scala製機械学習サーバ「Apache PredictionIO」Scala製機械学習サーバ「Apache PredictionIO」
Scala製機械学習サーバ「Apache PredictionIO」
takezoe
 
ネタじゃないScala.js
ネタじゃないScala.jsネタじゃないScala.js
ネタじゃないScala.js
takezoe
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
takezoe
 
Play2実践tips集
Play2実践tips集Play2実践tips集
Play2実践tips集
takezoe
 
Scala界隈の近況
Scala界隈の近況Scala界隈の近況
Scala界隈の近況
takezoe
 
そんなトランザクションマネージャで大丈夫か?
そんなトランザクションマネージャで大丈夫か?そんなトランザクションマネージャで大丈夫か?
そんなトランザクションマネージャで大丈夫か?
takezoe
 

More from takezoe (20)

Journey of Migrating Millions of Queries on The Cloud
Journey of Migrating Millions of Queries on The CloudJourney of Migrating Millions of Queries on The Cloud
Journey of Migrating Millions of Queries on The Cloud
 
GitBucket: Open source self-hosting Git server built by Scala
GitBucket: Open source self-hosting Git server built by ScalaGitBucket: Open source self-hosting Git server built by Scala
GitBucket: Open source self-hosting Git server built by Scala
 
Testing Distributed Query Engine as a Service
Testing Distributed Query Engine as a ServiceTesting Distributed Query Engine as a Service
Testing Distributed Query Engine as a Service
 
Revisit Dependency Injection in scala
Revisit Dependency Injection in scalaRevisit Dependency Injection in scala
Revisit Dependency Injection in scala
 
How to keep maintainability of long life Scala applications
How to keep maintainability of long life Scala applicationsHow to keep maintainability of long life Scala applications
How to keep maintainability of long life Scala applications
 
頑張りすぎないScala
頑張りすぎないScala頑張りすぎないScala
頑張りすぎないScala
 
GitBucket: Git Centric Software Development Platform by Scala
GitBucket:  Git Centric Software Development Platform by ScalaGitBucket:  Git Centric Software Development Platform by Scala
GitBucket: Git Centric Software Development Platform by Scala
 
Non-Functional Programming in Scala
Non-Functional Programming in ScalaNon-Functional Programming in Scala
Non-Functional Programming in Scala
 
Scala警察のすすめ
Scala警察のすすめScala警察のすすめ
Scala警察のすすめ
 
Scala製機械学習サーバ「Apache PredictionIO」
Scala製機械学習サーバ「Apache PredictionIO」Scala製機械学習サーバ「Apache PredictionIO」
Scala製機械学習サーバ「Apache PredictionIO」
 
The best of AltJava is Xtend
The best of AltJava is XtendThe best of AltJava is Xtend
The best of AltJava is Xtend
 
Java9 and Project Jigsaw
Java9 and Project JigsawJava9 and Project Jigsaw
Java9 and Project Jigsaw
 
markedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVM
 
ネタじゃないScala.js
ネタじゃないScala.jsネタじゃないScala.js
ネタじゃないScala.js
 
Excel方眼紙を支えるJava技術 2015
Excel方眼紙を支えるJava技術 2015Excel方眼紙を支えるJava技術 2015
Excel方眼紙を支えるJava技術 2015
 
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalaビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
 
GitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by ScalaGitBucket: The perfect Github clone by Scala
GitBucket: The perfect Github clone by Scala
 
Play2実践tips集
Play2実践tips集Play2実践tips集
Play2実践tips集
 
Scala界隈の近況
Scala界隈の近況Scala界隈の近況
Scala界隈の近況
 
そんなトランザクションマネージャで大丈夫か?
そんなトランザクションマネージャで大丈夫か?そんなトランザクションマネージャで大丈夫か?
そんなトランザクションマネージャで大丈夫か?
 

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Macro in Scala

  • 1. Macro in Scala Naoki Takezoe @takezoen BizReach, Inc 1 Oct. 2016 #渋谷java 17th
  • 3. C Expand special directive in source code before compilation by pre-processor #define square(x) ((x) * (x)) printf("i * i = %dn", i, square(i)); #define DEBUG #ifdef DEBUG printf("debug: i = %dn", i) #endif
  • 4. Lisp (also Scala or Rust) Generate AST in compile-time (defmacro when (test &body body) `(if ,test (progn ,@body))) (progn (when (= 1 1) (print "Hello,") (print "World!!"))) (progn (if (= 1 1) (progn (print "Hello,") (print "World!!")))) Expand by Macro
  • 5. Example in Scala def assert(cond: Boolean, msg: String): Unit = macro assertImpl def assertImpl(c: Context) (cond: c.Expr[Boolean], msg: c.Expr[String]) = { import c.universe._ q"if(!$cond){ throw new AssertionError($msg) }" }
  • 6. Example in Scala assert(i == 1, "i does not 1") if(i == 1){ throw new AssertionError("i does not 1") } Expand by Macro Note: Macro have to be compiled before main compilation
  • 8. Use cases ● Validation ● Type generation ● DSL ● Optimization without runtime overhead
  • 9. Quill ● Database access library for Scala ● Do in compile-time by macro ○ Translate typesafe DSL to SQL ○ SQL validation against real database val q = quote { query[Person].filter(p => p.age > 18) } // SELECT p.id, p.name, p.age FROM Person p WHERE p.age > 18 http://getquill.io/
  • 11. Macro type ● def macro ○ callable as same as normal function ● Macro annotation ○ triggered by annotation ○ requires Macro Paradise plug-in @main object Test { println("hello world") } object Test { def main(args: Array[String]): Unit = { println("hello world") } } Expand by Macro annotation
  • 12. How to construct AST? ● AST model ● reify ● Quasiquotes
  • 13. AST model def compileTimeImpl(c: Context)() = { Literal(Constant(new java.util.Date().toString)) }
  • 14. reify def assertImpl(c: Context) (cond: c.Expr[Boolean], msg: c.Expr[String]) = { import c.universe._ reify(if(!cond.splice){ throw new AssertionError(msg.splice) }) }
  • 15. Quasiquotes def assertImpl(c: Context) (cond: c.Expr[Boolean], msg: c.Expr[String]) = { import c.universe._ q"if(!$cond){ throw new AssertionError($msg) }" }
  • 16. Future: scala.mata ● Metaprogramming toolkit for Scala ● Replace scala.reflect ○ More simple and safe ● Scala Macro will move to scala.meta based ○ Only Macro annotation is available by Macro Paradise plug-in currently