SlideShare a Scribd company logo
Introduction to
QUASIQUOTES
By :-
SAHIL SAWHNEY
Software Consultant
KNOLDUS SOFTWARE LLP
By :-
SAHIL SAWHNEY
Software Consultant
KNOLDUS SOFTWARE LLP
Agenda
● Interpolators, a recap.
● What are quasiqoute?
● Required dependencies and imports.
● ShowRaw and showCode
● Lifting, Unlifting
● Compiling and executing ASTs
● Use case
● References
Revisiting Interpolators
➔ It is a mechanism that enable us to
sew/embed/bind WORDS in between a
processed/unprocessed string literal.
➔ We learned about s, raw and f string
interpolators
➔ Now let us uncover what quotation is which is
based on the fundamental of string
interpolators
What are Quasiquotes?
Quasiquotes are a neat notation that lets you
manipulate Scala syntax trees (AST) with
ease. Quotation syntax is in just another
usage of extensible string interpolation.
How neat are they?
val tree = q"i am { a quasiquote }"
and we have our AST.
What just happened?
The code wrapped inside q”...” is picked up and
an AST is formed from it.
NOTE →
The expression yielded by q”...” is just a tree
which is neither compiled nor executed
Justification
What according to you shall be the output for :
● scalac -Xshow-phases
(no compilation has occurred)
● Q”10 / 0”
(no execution has occurred)
Dependencies and imports.
➔ Dependencies :
"org.scala-lang" % "scala-reflect" % "2.11.8"
➔ Imports :
import scala.reflect.runtime.universe
import universe._
showRaw and showCode
➔ Understanding the pretty printers with example :
showCode : AST ––> equivalent source code
showRaw : AST ––> organization of the tree
Comparing trees
➔ ‘equalsStructure’ is used to determine if two
AST’s are structurally equal or not.
➔ Returns a true if AST are same.
q"I work at knoldus" equalsStructure q”{your
guess}”
Unqouting
➔Whenever we unquote an expression of Tree
type in a quasiquote, it will structurally
substitute that tree into the location.
➔Val a = q"class AAA"
➔Val b = q"class BBB"
➔q”$a + $b”
Splicing
➔Splicing is a way to unquote a variable number
of elements
➔One possible example can be a method call.
Discuss Example 2
Lifting
● Lifting is an extensible way to unquote custom data types
in quasiquotes.
● Int, String, Float (basic types) are all Liftable by default
● Its just
“ T –—> Tree “
val no =5
q”$no + $no”
Lifting cont..
● Liftable type is just a trait with a single abstract method that
defines a mapping of given type to tree
trait Liftable[T] {
def apply(value: T): Tree
}
● Whenever there is an implicit value of Liftable[T] available,
one can unquote T (our custom type) in quasiquotes. This
design pattern is known as a type class.
Lifting Custom Types
Demonstrating an Example of case class (most widely used
way to implement custom types in Scala) :-
case class Student(name: String, age: Int)
object Student {
implicit val lift = Liftable[Student] { stu =>
q"_root_.Student(${stu.name}, ${stu.age})"
}
}
Unlifting
● Unlifting is the reverse operation to lifting.
● It takes a tree and recovers value from it.
● Its just “ Tree –—> Option[T] “ . Why option?
val q"${left: Int} + ${right: Int}" = q"2 + 2"
Unlifting Cont..
● Unliftable type is just a trait with a single abstract method
that defines a mapping of given type to tree.
trait Unliftable[T] {
def unapply(tree: Tree): Option[T]
}
● Due to the fact that tree might not be a representation of
our data type, the return type of unapply is Option[T]
rather than just T
Unlifting Custom Types
Just add following to previous example
implicit val unliftIt = Unliftable[Student] {
case q"Student(${name: String}, ${age: Int})" =>
Student(name, age)
}
Example 3
Compiling and executing the
AST
Toolbox api serves the purpose of compiling the
AST.
Dependencies →
"org.scala-lang" % "scala-compiler" % "2.11.8"
Imports ->
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
Compiling
The AST can be compiled using the compile
method of Toolbox with following signature :
abstract def compile(tree : U.Tree): () Any⇒
It throws an compilation error if compilation fails.
Executing
The AST can be compiled and executed using the
eval method of Toolbox with following signature :
abstract def eval(tree : U.Tree): Any
It throws an compilation error if compilation fails
and runtime error if execution fails.
Use cases
● Easy AST manipulation
● Offline code generation(AST to corrosponding
code using showCode method)
● Just in time compilation using Toolbox api
References
http://www.scala-lang.org/api/2.12.0-M4/scala-compiler
http://docs.scala-lang.org/overviews/quasiquotes/intro
https://www.youtube.com/watch?v=_c6SMsZNxms
http://www.scala-lang.org/api/2.12.0-M4/scala-compiler
http://docs.scala-lang.org/overviews/quasiquotes/intro
https://www.youtube.com/watch?v=_c6SMsZNxms
Thank You !!!

More Related Content

Viewers also liked

Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lightbend
 
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
Lightbend
 

Viewers also liked (20)

Event sourcing with Eventuate
Event sourcing with EventuateEvent sourcing with Eventuate
Event sourcing with Eventuate
 
Walk-through: Amazon ECS
Walk-through: Amazon ECSWalk-through: Amazon ECS
Walk-through: Amazon ECS
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Introduction to BDD
Introduction to BDDIntroduction to BDD
Introduction to BDD
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
 
HTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventionsHTML5, CSS, JavaScript Style guide and coding conventions
HTML5, CSS, JavaScript Style guide and coding conventions
 
Deep dive into sass
Deep dive into sassDeep dive into sass
Deep dive into sass
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State Machine
 
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
 
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Oracle Database 12c Essentials 1Z0-497 exam questions
Oracle Database 12c Essentials 1Z0-497 exam questionsOracle Database 12c Essentials 1Z0-497 exam questions
Oracle Database 12c Essentials 1Z0-497 exam questions
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Getting Started With AureliaJs
Getting Started With AureliaJsGetting Started With AureliaJs
Getting Started With AureliaJs
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Introduction to Scala JS
Introduction to Scala JSIntroduction to Scala JS
Introduction to Scala JS
 
Realm Mobile Database - An Introduction
Realm Mobile Database - An IntroductionRealm Mobile Database - An Introduction
Realm Mobile Database - An Introduction
 
String interpolation
String interpolationString interpolation
String interpolation
 

Similar to Introduction to Quasiquotes

Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4
Bryan O'Sullivan
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 

Similar to Introduction to Quasiquotes (20)

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scala
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Java session 3
Java session 3Java session 3
Java session 3
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Container Classes
Container ClassesContainer Classes
Container Classes
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Working with shapes
Working with shapesWorking with shapes
Working with shapes
 
Intro toswift1
Intro toswift1Intro toswift1
Intro toswift1
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

Using InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in JmeterUsing InfluxDB for real-time monitoring in Jmeter
Using InfluxDB for real-time monitoring in Jmeter
 
Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)Intoduction to KubeVela Presentation (DevOps)
Intoduction to KubeVela Presentation (DevOps)
 
Stakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) PresentationStakeholder Management (Project Management) Presentation
Stakeholder Management (Project Management) Presentation
 
Introduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) PresentationIntroduction To Kaniko (DevOps) Presentation
Introduction To Kaniko (DevOps) Presentation
 
Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)Efficient Test Environments with Infrastructure as Code (IaC)
Efficient Test Environments with Infrastructure as Code (IaC)
 
Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)Exploring Terramate DevOps (Presentation)
Exploring Terramate DevOps (Presentation)
 
Clean Code in Test Automation Differentiating Between the Good and the Bad
Clean Code in Test Automation  Differentiating Between the Good and the BadClean Code in Test Automation  Differentiating Between the Good and the Bad
Clean Code in Test Automation Differentiating Between the Good and the Bad
 
Integrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test AutomationIntegrating AI Capabilities in Test Automation
Integrating AI Capabilities in Test Automation
 
State Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptxState Management with NGXS in Angular.pptx
State Management with NGXS in Angular.pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)OAuth2 Implementation Presentation (Java)
OAuth2 Implementation Presentation (Java)
 
Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 

Recently uploaded

AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 

Recently uploaded (20)

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 

Introduction to Quasiquotes

  • 1. Introduction to QUASIQUOTES By :- SAHIL SAWHNEY Software Consultant KNOLDUS SOFTWARE LLP By :- SAHIL SAWHNEY Software Consultant KNOLDUS SOFTWARE LLP
  • 2. Agenda ● Interpolators, a recap. ● What are quasiqoute? ● Required dependencies and imports. ● ShowRaw and showCode ● Lifting, Unlifting ● Compiling and executing ASTs ● Use case ● References
  • 3. Revisiting Interpolators ➔ It is a mechanism that enable us to sew/embed/bind WORDS in between a processed/unprocessed string literal. ➔ We learned about s, raw and f string interpolators ➔ Now let us uncover what quotation is which is based on the fundamental of string interpolators
  • 4. What are Quasiquotes? Quasiquotes are a neat notation that lets you manipulate Scala syntax trees (AST) with ease. Quotation syntax is in just another usage of extensible string interpolation. How neat are they? val tree = q"i am { a quasiquote }" and we have our AST.
  • 5. What just happened? The code wrapped inside q”...” is picked up and an AST is formed from it. NOTE → The expression yielded by q”...” is just a tree which is neither compiled nor executed
  • 6. Justification What according to you shall be the output for : ● scalac -Xshow-phases (no compilation has occurred) ● Q”10 / 0” (no execution has occurred)
  • 7. Dependencies and imports. ➔ Dependencies : "org.scala-lang" % "scala-reflect" % "2.11.8" ➔ Imports : import scala.reflect.runtime.universe import universe._
  • 8. showRaw and showCode ➔ Understanding the pretty printers with example : showCode : AST ––> equivalent source code showRaw : AST ––> organization of the tree
  • 9. Comparing trees ➔ ‘equalsStructure’ is used to determine if two AST’s are structurally equal or not. ➔ Returns a true if AST are same. q"I work at knoldus" equalsStructure q”{your guess}”
  • 10. Unqouting ➔Whenever we unquote an expression of Tree type in a quasiquote, it will structurally substitute that tree into the location. ➔Val a = q"class AAA" ➔Val b = q"class BBB" ➔q”$a + $b”
  • 11. Splicing ➔Splicing is a way to unquote a variable number of elements ➔One possible example can be a method call. Discuss Example 2
  • 12. Lifting ● Lifting is an extensible way to unquote custom data types in quasiquotes. ● Int, String, Float (basic types) are all Liftable by default ● Its just “ T –—> Tree “ val no =5 q”$no + $no”
  • 13. Lifting cont.. ● Liftable type is just a trait with a single abstract method that defines a mapping of given type to tree trait Liftable[T] { def apply(value: T): Tree } ● Whenever there is an implicit value of Liftable[T] available, one can unquote T (our custom type) in quasiquotes. This design pattern is known as a type class.
  • 14. Lifting Custom Types Demonstrating an Example of case class (most widely used way to implement custom types in Scala) :- case class Student(name: String, age: Int) object Student { implicit val lift = Liftable[Student] { stu => q"_root_.Student(${stu.name}, ${stu.age})" } }
  • 15. Unlifting ● Unlifting is the reverse operation to lifting. ● It takes a tree and recovers value from it. ● Its just “ Tree –—> Option[T] “ . Why option? val q"${left: Int} + ${right: Int}" = q"2 + 2"
  • 16. Unlifting Cont.. ● Unliftable type is just a trait with a single abstract method that defines a mapping of given type to tree. trait Unliftable[T] { def unapply(tree: Tree): Option[T] } ● Due to the fact that tree might not be a representation of our data type, the return type of unapply is Option[T] rather than just T
  • 17. Unlifting Custom Types Just add following to previous example implicit val unliftIt = Unliftable[Student] { case q"Student(${name: String}, ${age: Int})" => Student(name, age) } Example 3
  • 18. Compiling and executing the AST Toolbox api serves the purpose of compiling the AST. Dependencies → "org.scala-lang" % "scala-compiler" % "2.11.8" Imports -> import scala.reflect.runtime.currentMirror import scala.tools.reflect.ToolBox
  • 19. Compiling The AST can be compiled using the compile method of Toolbox with following signature : abstract def compile(tree : U.Tree): () Any⇒ It throws an compilation error if compilation fails.
  • 20. Executing The AST can be compiled and executed using the eval method of Toolbox with following signature : abstract def eval(tree : U.Tree): Any It throws an compilation error if compilation fails and runtime error if execution fails.
  • 21. Use cases ● Easy AST manipulation ● Offline code generation(AST to corrosponding code using showCode method) ● Just in time compilation using Toolbox api