SlideShare a Scribd company logo
1 of 58
Download to read offline
What's a macro? 
Learning by Examples 
Takako Shimamoto 
BizReach, Inc
What to Talk About 
• What are macros? 
• Good thing about macros 
• Actual use cases of macros 
• Future of macros
Are you using 
macros? 
If “Yes",
The Fab You!
Because 
• Using macros is easy, developing macros is hard
What are macros? 
• Code that generates code 
• Not textual code generation
What are macros? 
• An experimental feature of 2.10+ 
• Compiler invokes functions
Before macros 
• Ad-hoc textual code generation by sbt plugin 
• Compile-time AST operation by compiler plugin
Why macros are necessary? 
• Code is made simple 
• Efficiency improved
Macro is on 
your side!
To use macros? 
• Need to be enabled explicitly 
• import scala.language.experimental.macros 
• -language:experimental.macros
Notes 
• Macros are separate compilation 
• Macro implementations need to be compiled before 
the main compilation
Def Macros
Def Macros 
• Def macros replace well-typed terms with other 
well-typed terms 
• Can contain arbitrary Scala constructs
Practical 
example 
Scala Logging
Where? 
you call 
logger.debug(s"Some $expensive message!") 
replaced by macros 
if (logger.isDebugEnabled) 
logger.debug(s"Some $expensive message!")
Macro definition 
• Starts with the conditional keyword macro 
• Followed by a static macro implementation method
Implementation of the macro 
• Takes several parameter lists
Implementation of the macro 
• Takes several parameter lists 
First comes a single 
parameter, of type 
Context
Implementation of the macro 
• Takes several parameter lists 
Macro definition 
Next, followed by a list of 
parameters that have the 
same names as the macro 
definition parameters
Implementation of the macro 
• The original macro parameter has 
• type T 
• A macro implementation parameter has 
• type c.Expr[T]
Quasiquotes 
• q"..." string interpolators that build code 
• Unnecessary to directly implement the AST 
• To use the quasiquotes from the macro, just write 
import c.universe._
Quasiquotes 
• Using the showRaw, it is possible to see the AST
Goodness 
• The hard to comprehend notion of meta 
programming 
• def macros are similar to the concept of a typed 
method call
Practical 
example 
specs2
Where? 
• To use macros to automatically generate matchers 
for any complex type 
• MatcherMacros trait
Where? 
case class Cat(name: String, age: Int) 
! 
// your test case 
val cat = Cat(name = "Tom", age = 2) 
cat must matchA[Cat].name("Tom") 
you call
Where? 
replaced by macros 
def matchACat( 
name: Matcher[String] = AlwaysMatcher(), 
age: Matcher[Int] = AlwaysMatcher() 
): Matcher[Cat] = 
name ^^ {(cat: Cat) => cat.name} and 
age ^^ {(cat: Cat) => cat.age}
Macro definition 
• Generics 
• Has type parameters
Implementation of the macro 
• Type tags(actual type arguments) will be passed 
along when the macro is expanded
Implementation of the macro 
• Type tags(actual type arguments) will be passed 
along when the macro is expanded 
Come with 
WeakTypeTag 
context bounds
Goodness 
• DRY approach 
• Usage is fairly simple
Blackbox vs Whitebox 
• From 2.11 
• Not implemented in 2.10 or in macro paradise 
• in 2.12, only include blackbox macros
Blackbox vs Whitebox 
• 2.10 
• scala.reflect.macros.Context 
• 2.11 
• scala.reflect.macros.blackbox.Context 
• scala.reflect.macros.whitebox.Context
Why distinction? 
• Type specification of macro is curious 
class Foo 
class Bar extends Foo 
Scala 2.10 
! 
object FooExample { 
def foo: Foo = macro foo_impl 
def foo_impl(c: Context): c.Expr[Foo] = 
c.Expr[Foo](c.universe.reify(new Bar).tree) 
}
Why distinction? 
scala> FooExample.foo 
res0: Bar = Bar@4118f8dd 
• Type checking during macro expansion 
• Not affect after expansion
Blackbox restrictions 
• Type parameters of macro affect the type of after 
macro expansion 
• When blackbox macro is used, techniques such as 
Implicit Macros will not work
No restrictions Whitebox 
• Same as 2.10 def macros 
• Everything that could be done with macros in 2.10 
should be possible in 2.11
Practical 
example 
Spire
Appendix - What is Spire? 
• A numeric library for Scala 
• Using features such as macros, type classes 
• Fast and Precise
Where? 
• Using string interpolation and macros, Spire 
provides convenient syntax for number types 
• Evaluated at compile-time
Macro definition 
• As usual 
string interpolation
Implementation of the macro 
• Syntax check at compile-time
Implementation of the macro 
• Syntax check at compile-time 
Occur at compile-time 
if any errors 
encounter
Goodness 
• Static (compile-time) type check 
• Runtime error decrease
But, has 
weak side.
Current state 
• Optimized towards compiler developers, not library 
users 
Complicated!!
Scala 2.12 (plan) 
• Not introduce new features 
• Bugfixes and stability improvements 
• Mention later why reason…
scala.meta 
• A new experimental API for metaprogramming 
• Formerly known as Project Palladium
scala.meta 
• Implemented in a library shipped separately from 
the official Scala distribution 
• The first milestone release is scheduled for this fall
The goal of scala.meta 
• Metaprogramming easy 
• New API is going to greatly simplify writing 
macros 
• Not require knowledge of compiler internals
Language model 
• All represented with trees 
Types 
Modifiers 
… 
Names 
Trees 
scala.meta 
Terms 
Symbols
Language model 
• Keeps all the information about the program 
• Comments also remain 
• No information is lost anymore
Manner of utilization 
• Code generation 
• Static type checking 
• etc…
Summary 
• Macros are actively used in the OSS library 
• Can be more efficiently and safely programming 
• Scala macros are evolving!
Thanks!!

More Related Content

What's hot

Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1Todor Kolev
 
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 ScalaDerek Chen-Becker
 
Dmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script TechnologiesDmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script TechnologiesLogeekNightUkraine
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsKwangshin Oh
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz SAurabh PRajapati
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsqlArun Sial
 
Design patterns - Singleton&Command
Design patterns - Singleton&CommandDesign patterns - Singleton&Command
Design patterns - Singleton&CommandKai Aras
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapDave Orme
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8Takipi
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsqlArun Sial
 

What's hot (20)

Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
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
 
Java ce241
Java ce241Java ce241
Java ce241
 
Dmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script TechnologiesDmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script Technologies
 
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIsCS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
CS6270 Virtual Machines - Java Virtual Machine Architecture and APIs
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Design patterns - Singleton&Command
Design patterns - Singleton&CommandDesign patterns - Singleton&Command
Design patterns - Singleton&Command
 
Refactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 RecapRefactoring to Scala DSLs and LiftOff 2009 Recap
Refactoring to Scala DSLs and LiftOff 2009 Recap
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Objective-C: Good and Bad
Objective-C: Good and BadObjective-C: Good and Bad
Objective-C: Good and Bad
 
Scala tutorial
Scala tutorialScala tutorial
Scala tutorial
 
Java Virtual Machine
Java Virtual MachineJava Virtual Machine
Java Virtual Machine
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsql
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Macro-processor
Macro-processorMacro-processor
Macro-processor
 

Viewers also liked

33443223 system-software-unit-iv
33443223 system-software-unit-iv33443223 system-software-unit-iv
33443223 system-software-unit-ivShaniya Fathimuthu
 
Macros...presentation
Macros...presentationMacros...presentation
Macros...presentationfika sweety
 
Scio - A Scala API for Google Cloud Dataflow & Apache Beam
Scio - A Scala API for Google Cloud Dataflow & Apache BeamScio - A Scala API for Google Cloud Dataflow & Apache Beam
Scio - A Scala API for Google Cloud Dataflow & Apache BeamNeville Li
 
Chase Up Success Story
Chase Up Success StoryChase Up Success Story
Chase Up Success StoryMuzamil Rehman
 
Supermarket Presentation
Supermarket Presentation Supermarket Presentation
Supermarket Presentation Favian Chua
 
Extra Easy Supermarket Design
Extra Easy Supermarket Design Extra Easy Supermarket Design
Extra Easy Supermarket Design Manav Shrivastav
 
Reed’s superstore case study analysis
Reed’s superstore case study analysisReed’s superstore case study analysis
Reed’s superstore case study analysisSaurabh Mhase
 
Metro, A Presentation of Production Management
Metro, A Presentation of Production ManagementMetro, A Presentation of Production Management
Metro, A Presentation of Production ManagementMuti ur Rahman Khan Lodhi
 
System Programming Unit II
System Programming Unit IISystem Programming Unit II
System Programming Unit IIManoj Patil
 
Grocery trends presentation skills
Grocery trends presentation skillsGrocery trends presentation skills
Grocery trends presentation skillsSteven Conway
 
Power point presentation (grocery store)
Power point presentation (grocery store)Power point presentation (grocery store)
Power point presentation (grocery store)Alina Hacopian
 
Hyperstar Retail storepresntation
Hyperstar Retail storepresntationHyperstar Retail storepresntation
Hyperstar Retail storepresntationHira Farooq
 
Macro environment
Macro environmentMacro environment
Macro environmentRicha Puri
 

Viewers also liked (20)

Learning
LearningLearning
Learning
 
33443223 system-software-unit-iv
33443223 system-software-unit-iv33443223 system-software-unit-iv
33443223 system-software-unit-iv
 
Macros...presentation
Macros...presentationMacros...presentation
Macros...presentation
 
Scio - A Scala API for Google Cloud Dataflow & Apache Beam
Scio - A Scala API for Google Cloud Dataflow & Apache BeamScio - A Scala API for Google Cloud Dataflow & Apache Beam
Scio - A Scala API for Google Cloud Dataflow & Apache Beam
 
Chase Up Success Story
Chase Up Success StoryChase Up Success Story
Chase Up Success Story
 
Supermarket Presentation
Supermarket Presentation Supermarket Presentation
Supermarket Presentation
 
Extra Easy Supermarket Design
Extra Easy Supermarket Design Extra Easy Supermarket Design
Extra Easy Supermarket Design
 
Reed’s superstore case study analysis
Reed’s superstore case study analysisReed’s superstore case study analysis
Reed’s superstore case study analysis
 
Macro
MacroMacro
Macro
 
Imtiaz super market
Imtiaz super marketImtiaz super market
Imtiaz super market
 
Metro, A Presentation of Production Management
Metro, A Presentation of Production ManagementMetro, A Presentation of Production Management
Metro, A Presentation of Production Management
 
System Programming Unit II
System Programming Unit IISystem Programming Unit II
System Programming Unit II
 
Supermarket
SupermarketSupermarket
Supermarket
 
Device Drivers
Device DriversDevice Drivers
Device Drivers
 
Grocery trends presentation skills
Grocery trends presentation skillsGrocery trends presentation skills
Grocery trends presentation skills
 
Sorting
SortingSorting
Sorting
 
Supermarkets
SupermarketsSupermarkets
Supermarkets
 
Power point presentation (grocery store)
Power point presentation (grocery store)Power point presentation (grocery store)
Power point presentation (grocery store)
 
Hyperstar Retail storepresntation
Hyperstar Retail storepresntationHyperstar Retail storepresntation
Hyperstar Retail storepresntation
 
Macro environment
Macro environmentMacro environment
Macro environment
 

Similar to What's a macro?: Learning by Examples

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のマクロに実用例から触れてみよう!scalaconfjp
 
Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosEmmett Ross
 
Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 dcubeio
 
Micronaut Deep Dive - Devnexus 2019
Micronaut Deep Dive - Devnexus 2019Micronaut Deep Dive - Devnexus 2019
Micronaut Deep Dive - Devnexus 2019graemerocher
 
Deploying MLlib for Scoring in Structured Streaming with Joseph Bradley
Deploying MLlib for Scoring in Structured Streaming with Joseph BradleyDeploying MLlib for Scoring in Structured Streaming with Joseph Bradley
Deploying MLlib for Scoring in Structured Streaming with Joseph BradleyDatabricks
 
Micronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless EraMicronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless Eragraemerocher
 
Making Scala Faster: 3 Expert Tips For Busy Development Teams
Making Scala Faster: 3 Expert Tips For Busy Development TeamsMaking Scala Faster: 3 Expert Tips For Busy Development Teams
Making Scala Faster: 3 Expert Tips For Busy Development TeamsLightbend
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...AboutYouGmbH
 
White and Black Magic on the JVM
White and Black Magic on the JVMWhite and Black Magic on the JVM
White and Black Magic on the JVMIvaylo Pashov
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure DataTaro L. Saito
 
44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...
44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...
44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...44CON
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmerselliando dias
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceESUG
 
TypeScript and Angular2 (Love at first sight)
TypeScript and Angular2 (Love at first sight)TypeScript and Angular2 (Love at first sight)
TypeScript and Angular2 (Love at first sight)Igor Talevski
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaAlex Moskvin
 
Scala io2013 : Our journey from UML/MDD to Scala macros
Scala io2013 : Our journey from UML/MDD to Scala macrosScala io2013 : Our journey from UML/MDD to Scala macros
Scala io2013 : Our journey from UML/MDD to Scala macrosebiznext
 
In-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDIn-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDStop Coding
 
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceCOMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceAntonio García-Domínguez
 

Similar to What's a macro?: Learning by Examples (20)

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のマクロに実用例から触れてみよう!
 
Getting started with CATIA V5 Macros
Getting started with CATIA V5 MacrosGetting started with CATIA V5 Macros
Getting started with CATIA V5 Macros
 
Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217 Scalaマクロ入門 bizr20170217
Scalaマクロ入門 bizr20170217
 
Micronaut Deep Dive - Devnexus 2019
Micronaut Deep Dive - Devnexus 2019Micronaut Deep Dive - Devnexus 2019
Micronaut Deep Dive - Devnexus 2019
 
Deploying MLlib for Scoring in Structured Streaming with Joseph Bradley
Deploying MLlib for Scoring in Structured Streaming with Joseph BradleyDeploying MLlib for Scoring in Structured Streaming with Joseph Bradley
Deploying MLlib for Scoring in Structured Streaming with Joseph Bradley
 
Micronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless EraMicronaut: Evolving Java for the Microservices and Serverless Era
Micronaut: Evolving Java for the Microservices and Serverless Era
 
Making Scala Faster: 3 Expert Tips For Busy Development Teams
Making Scala Faster: 3 Expert Tips For Busy Development TeamsMaking Scala Faster: 3 Expert Tips For Busy Development Teams
Making Scala Faster: 3 Expert Tips For Busy Development Teams
 
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
Stefan Richter - Writing simple, readable and robust code: Examples in Java, ...
 
White and Black Magic on the JVM
White and Black Magic on the JVMWhite and Black Magic on the JVM
White and Black Magic on the JVM
 
Scala at Treasure Data
Scala at Treasure DataScala at Treasure Data
Scala at Treasure Data
 
44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...
44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...
44CON London 2015 - Reverse engineering and exploiting font rasterizers: the ...
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmers
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
Unit 4 sp macro
Unit 4 sp macroUnit 4 sp macro
Unit 4 sp macro
 
TypeScript and Angular2 (Love at first sight)
TypeScript and Angular2 (Love at first sight)TypeScript and Angular2 (Love at first sight)
TypeScript and Angular2 (Love at first sight)
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
 
Scala io2013 : Our journey from UML/MDD to Scala macros
Scala io2013 : Our journey from UML/MDD to Scala macrosScala io2013 : Our journey from UML/MDD to Scala macros
Scala io2013 : Our journey from UML/MDD to Scala macros
 
In-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCDIn-depth look at the Flex compiler and HFCD
In-depth look at the Flex compiler and HFCD
 
Core JavaScript
Core JavaScriptCore JavaScript
Core JavaScript
 
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceCOMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
 

More from chibochibo

Tour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 MinutesTour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 Minuteschibochibo
 
Crawler Commons
Crawler CommonsCrawler Commons
Crawler Commonschibochibo
 
Deadly Code! (seriously) Blocking & Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking & Hyper Context Switching PatternDeadly Code! (seriously) Blocking & Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking & Hyper Context Switching Patternchibochibo
 
Dynamic SQL in doobie
Dynamic SQL in doobieDynamic SQL in doobie
Dynamic SQL in doobiechibochibo
 
Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?chibochibo
 
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 -chibochibo
 
Quartzでcronを範囲検索したい
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したいchibochibo
 
ビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingchibochibo
 
nioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったnioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったchibochibo
 
Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-chibochibo
 
Spark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with ElasticsearchSpark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with Elasticsearchchibochibo
 
Spring Boot Introduction
Spring Boot IntroductionSpring Boot Introduction
Spring Boot Introductionchibochibo
 

More from chibochibo (14)

Tour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 MinutesTour of Apache PredictionIO in 10 Minutes
Tour of Apache PredictionIO in 10 Minutes
 
Crawler Commons
Crawler CommonsCrawler Commons
Crawler Commons
 
LocalStack
LocalStackLocalStack
LocalStack
 
Deadly Code! (seriously) Blocking & Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking & Hyper Context Switching PatternDeadly Code! (seriously) Blocking & Hyper Context Switching Pattern
Deadly Code! (seriously) Blocking & Hyper Context Switching Pattern
 
Dynamic SQL in doobie
Dynamic SQL in doobieDynamic SQL in doobie
Dynamic SQL in doobie
 
Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?Is spark streaming based on reactive streams?
Is spark streaming based on reactive streams?
 
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 -
 
Quartzでcronを範囲検索したい
Quartzでcronを範囲検索したいQuartzでcronを範囲検索したい
Quartzでcronを範囲検索したい
 
ビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streamingビッグじゃなくても使えるSpark Streaming
ビッグじゃなくても使えるSpark Streaming
 
nioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になったnioで作ったBufferedWriterに変えたら例外になった
nioで作ったBufferedWriterに変えたら例外になった
 
Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-Spark Streaming on AWS -S3からKinesisへ-
Spark Streaming on AWS -S3からKinesisへ-
 
Spark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with ElasticsearchSpark in small or middle scale data processing with Elasticsearch
Spark in small or middle scale data processing with Elasticsearch
 
Spring Boot Introduction
Spring Boot IntroductionSpring Boot Introduction
Spring Boot Introduction
 
Slick入門
Slick入門Slick入門
Slick入門
 

Recently uploaded

Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
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.jsAndolasoft Inc
 
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...ICS
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
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 PrecisionSolGuruz
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
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...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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 🔝✔️✔️Delhi Call girls
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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 WorkerThousandEyes
 

Recently uploaded (20)

Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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
 
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...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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
 

What's a macro?: Learning by Examples

  • 1. What's a macro? Learning by Examples Takako Shimamoto BizReach, Inc
  • 2. What to Talk About • What are macros? • Good thing about macros • Actual use cases of macros • Future of macros
  • 3. Are you using macros? If “Yes",
  • 5. Because • Using macros is easy, developing macros is hard
  • 6. What are macros? • Code that generates code • Not textual code generation
  • 7. What are macros? • An experimental feature of 2.10+ • Compiler invokes functions
  • 8. Before macros • Ad-hoc textual code generation by sbt plugin • Compile-time AST operation by compiler plugin
  • 9. Why macros are necessary? • Code is made simple • Efficiency improved
  • 10. Macro is on your side!
  • 11. To use macros? • Need to be enabled explicitly • import scala.language.experimental.macros • -language:experimental.macros
  • 12. Notes • Macros are separate compilation • Macro implementations need to be compiled before the main compilation
  • 14. Def Macros • Def macros replace well-typed terms with other well-typed terms • Can contain arbitrary Scala constructs
  • 16. Where? you call logger.debug(s"Some $expensive message!") replaced by macros if (logger.isDebugEnabled) logger.debug(s"Some $expensive message!")
  • 17. Macro definition • Starts with the conditional keyword macro • Followed by a static macro implementation method
  • 18. Implementation of the macro • Takes several parameter lists
  • 19. Implementation of the macro • Takes several parameter lists First comes a single parameter, of type Context
  • 20. Implementation of the macro • Takes several parameter lists Macro definition Next, followed by a list of parameters that have the same names as the macro definition parameters
  • 21. Implementation of the macro • The original macro parameter has • type T • A macro implementation parameter has • type c.Expr[T]
  • 22. Quasiquotes • q"..." string interpolators that build code • Unnecessary to directly implement the AST • To use the quasiquotes from the macro, just write import c.universe._
  • 23. Quasiquotes • Using the showRaw, it is possible to see the AST
  • 24. Goodness • The hard to comprehend notion of meta programming • def macros are similar to the concept of a typed method call
  • 26. Where? • To use macros to automatically generate matchers for any complex type • MatcherMacros trait
  • 27. Where? case class Cat(name: String, age: Int) ! // your test case val cat = Cat(name = "Tom", age = 2) cat must matchA[Cat].name("Tom") you call
  • 28. Where? replaced by macros def matchACat( name: Matcher[String] = AlwaysMatcher(), age: Matcher[Int] = AlwaysMatcher() ): Matcher[Cat] = name ^^ {(cat: Cat) => cat.name} and age ^^ {(cat: Cat) => cat.age}
  • 29. Macro definition • Generics • Has type parameters
  • 30. Implementation of the macro • Type tags(actual type arguments) will be passed along when the macro is expanded
  • 31. Implementation of the macro • Type tags(actual type arguments) will be passed along when the macro is expanded Come with WeakTypeTag context bounds
  • 32. Goodness • DRY approach • Usage is fairly simple
  • 33. Blackbox vs Whitebox • From 2.11 • Not implemented in 2.10 or in macro paradise • in 2.12, only include blackbox macros
  • 34. Blackbox vs Whitebox • 2.10 • scala.reflect.macros.Context • 2.11 • scala.reflect.macros.blackbox.Context • scala.reflect.macros.whitebox.Context
  • 35. Why distinction? • Type specification of macro is curious class Foo class Bar extends Foo Scala 2.10 ! object FooExample { def foo: Foo = macro foo_impl def foo_impl(c: Context): c.Expr[Foo] = c.Expr[Foo](c.universe.reify(new Bar).tree) }
  • 36. Why distinction? scala> FooExample.foo res0: Bar = Bar@4118f8dd • Type checking during macro expansion • Not affect after expansion
  • 37. Blackbox restrictions • Type parameters of macro affect the type of after macro expansion • When blackbox macro is used, techniques such as Implicit Macros will not work
  • 38. No restrictions Whitebox • Same as 2.10 def macros • Everything that could be done with macros in 2.10 should be possible in 2.11
  • 40. Appendix - What is Spire? • A numeric library for Scala • Using features such as macros, type classes • Fast and Precise
  • 41. Where? • Using string interpolation and macros, Spire provides convenient syntax for number types • Evaluated at compile-time
  • 42. Macro definition • As usual string interpolation
  • 43. Implementation of the macro • Syntax check at compile-time
  • 44. Implementation of the macro • Syntax check at compile-time Occur at compile-time if any errors encounter
  • 45. Goodness • Static (compile-time) type check • Runtime error decrease
  • 46. But, has weak side.
  • 47. Current state • Optimized towards compiler developers, not library users Complicated!!
  • 48.
  • 49. Scala 2.12 (plan) • Not introduce new features • Bugfixes and stability improvements • Mention later why reason…
  • 50. scala.meta • A new experimental API for metaprogramming • Formerly known as Project Palladium
  • 51. scala.meta • Implemented in a library shipped separately from the official Scala distribution • The first milestone release is scheduled for this fall
  • 52. The goal of scala.meta • Metaprogramming easy • New API is going to greatly simplify writing macros • Not require knowledge of compiler internals
  • 53. Language model • All represented with trees Types Modifiers … Names Trees scala.meta Terms Symbols
  • 54. Language model • Keeps all the information about the program • Comments also remain • No information is lost anymore
  • 55.
  • 56. Manner of utilization • Code generation • Static type checking • etc…
  • 57. Summary • Macros are actively used in the OSS library • Can be more efficiently and safely programming • Scala macros are evolving!