SlideShare a Scribd company logo
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

PDF
Emscripten, asm.js, and billions of math ops
PDF
Let's Go-lang
PDF
Learning To Love Java Script Color
PDF
Learning To Love Java Script
PDF
Go for Rubyists
KEY
Coqによる証明駆動開発
PDF
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
KEY
Coq to Rubyによる証明駆動開発@名古屋ruby会議02
Emscripten, asm.js, and billions of math ops
Let's Go-lang
Learning To Love Java Script Color
Learning To Love Java Script
Go for Rubyists
Coqによる証明駆動開発
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Coq to Rubyによる証明駆動開発@名古屋ruby会議02

What's hot (15)

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

Viewers also liked (20)

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

Similar to Macro in Scala (20)

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

More from takezoe (20)

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

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
L1 - Introduction to python Backend.pptx
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Introduction to Artificial Intelligence
PPTX
ai tools demonstartion for schools and inter college
PDF
AI in Product Development-omnex systems
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPT
Introduction Database Management System for Course Database
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
medical staffing services at VALiNTRY
PDF
top salesforce developer skills in 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
L1 - Introduction to python Backend.pptx
Navsoft: AI-Powered Business Solutions & Custom Software Development
CHAPTER 2 - PM Management and IT Context
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Understanding Forklifts - TECH EHS Solution
Introduction to Artificial Intelligence
ai tools demonstartion for schools and inter college
AI in Product Development-omnex systems
Design an Analysis of Algorithms II-SECS-1021-03
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
How Creative Agencies Leverage Project Management Software.pdf
Introduction Database Management System for Course Database
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Odoo POS Development Services by CandidRoot Solutions
medical staffing services at VALiNTRY
top salesforce developer skills in 2025.pdf

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