SlideShare a Scribd company logo
Scala runtime Meta-Programming
About Me
Meir Maor
Chief Architect @ SparkBeyond
At SparkBeyond we leverage the collective
human knowledge to solve the world's toughest
problems
This Talk
Showcase Scala reflection, and compiler toolbox
Use a real guiding example to see how these are
used to solve a real problem
SparkBeyond
SparkBeyond generates code to solve machine
learning problems, leveraging world knowledge
Allows crafting deeply embedded pipelines to
explicitly transform your data
Guiding Example
● We would like to build a deeply embedded
framework to transform data.
● Multiple classes define actions
● Can be stacked together
● Embed user generated Scala code
● Auto generate a UI to input parameters for
actions.
● Allow annotating fields to guide UI generation
case class AddColumn(columnName: String,codeExpression: String) extends Action
{...}
case class SpecialParam(a: Int,b : Int => Int)
object SpecialAction {
val myMap = Map("mul2" -> SpecialParam(1,_ * 2),
"add1" -> SpecialParam(2,_ + 1),
"ident" -> SpecialParam(3, identity)
)
}
case class SpecialAction(@PossibleValuesMap(SpecialAction.myMap) foo:
SpecialParam) extends Action
Intro to Scala Meta Programming
Creating and using mirror
import reflect.runtime.universe._
val cm =
runtimeMirror(getClass.getClassLoader)
Know the players
● Type
● Symbol
● Tree
documentation reference: http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html
Type
val t=typeOf[List[Int]]
t: reflect.runtime.universe.Type =
scala.List[Int]
Compare with =:= or <:< or weak_<:<
Key methods: declarations, baseClasses,
BaseType, typeSymbol
Symbol
● If it has a name it has a Symbol
– Types, Members, parameters
Not a type, even TypeSymbol is less than a Type
val ts=t.typeSymbol
ts: reflect.runtime.universe.Symbol =
class List
Tree
● An Abstract Syntax Tree
val tree = Apply(Select(Ident(TermName("x")),
TermName("$plus")), List(Literal(Constant(2))))
tree: scala.reflect.runtime.universe.Apply = x.$plus(2)
val expr = reify { class Flower { def name = "Rose" } }
expr: scala.reflect.runtime.universe.Expr[Unit] = …
expr.tree
Get param list from primary ctr
scala> val typ = typeOf[AddColumn]
typ: reflect.runtime.universe.Type = AddColumn
val primary=typ.typeSymbol.asClass.primaryConstructor
primary: reflect.runtime.universe.Symbol = constructor AddColumn
//recall a method can have multiple param lists, hence flaten
val paramList = primary.asMethod.paramLists.flatten
paramList: List[reflect.runtime.universe.Symbol] = List(value
columnName, value codeExpression)
Code Generation
● Cglib – byte code generation library
● Compiling externally and loading with a fresh
classloader
● The unsafe way - mutate the existing
classloader
● Scala Compiler toolbox
UrlClassLoader
def getClassInstanceFromJar[T](jarFile: File, className:
String): T = {
val classLoader = new
scala.reflect.internal.util.ScalaClassLoader.URLClassLoader(Seq(ja
rFile.toURI.toURL), this.getClass.getClassLoader)
val mirror =
scala.reflect.runtime.universe.runtimeMirror(classLoader)
val classSymbol = mirror.staticClass(className)
val ctorSymbol = classSymbol.primaryConstructor.asMethod
val ctor =
mirror.reflectClass(classSymbol).reflectConstructor(ctorSymbol)
ctor.apply().asInstanceOf[T]
}
Mutate existing ClassLoader
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader)
ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system
classloader");
}//end try catch
}//end method
Compiler ToolBox
● Experimental (even more so than the rest of the reflection api)
import scala.tools.reflect.ToolBox
val tb = cm.mkToolBox()
● Parse, typecheck, eval
def run(code: String) = {
synchronized {
val tree = tb parse s"import scala._nimport Predef._n $code"
tb eval tree
}
}
Using the ToolBox
● Get User code fragment
● Add boilerplate function definition, useful
variables
● Parse and eval
● Apply function on new data
Annotations
● In Java you can easily read annotations reflectively at
runtime
● Annotations can only hold specific types:
– primitive
– String
– Class
– an Enum
– another Annotation
– an array of any of the above
Scala annotations
● Scala annotations are not Java annotations
● You can put anything in a Scala annotation
● But How do you read it?
Documentation: http://docs.scala-lang.org/overviews/reflection/annotations-names-scopes.html
Defining Scala Annotation
Extend StaticAnnotation to make it available at
Runtime
case class ValuesMap(vals: Map[String, Any]) extends
StaticAnnotation
Get annotations from a symbol
● Many things can be annotated
– A type, A Method, A parameter, a val/var
● Recall our example:
case class SpecialAction(@ValuesMap(SpecialAction.myMap) foo:
SpecialParam) extends Action
Get annotations from a symbol
val param: Symbol = longestParmList.head
param: reflect.runtime.universe.Symbol = value foo
val annotations = param.annotations
scala> annotations: List[reflect.runtime.universe.Annotation] =
List(com.sparkbeyond.runtime.util.misc.ValuesMap(SpecialAction.m
yMap)
Recreate Annotation Instance
scala> val tree=annotations.head.tree
tree: reflect.runtime.universe.Tree = new
com.sparkbeyond.runtime.util.misc.ValuesMap(SpecialAction.myMap)
scala> tb.eval(tb.untypecheck(tree))
res15: Any = ValuesMap(Map(mul2 -> SpecialParam(1,<function1>), add1 ->
SpecialParam(2,<function1>), ident -> SpecialParam(3,<function1>)))
Overcoming Erasure - RTTI
● Java Generics for better or worse get erased in
runtime
● We would like to be able to tell the Type of an
instance including Type Parameters
● In most cases this is possible in a meaningful
way.
What is my type?
case class OneIntSeq(a: Int) extends Seq[Int] {...}
case class MyCaseClass[T,U](e: T,o: Seq[U])
val v = MyCaseClass("foo",OneIntSeq(1))
We want a method, given v to produce:
MyCaseClass[String,Int]
val topType=cm.reflect(v).symbol.toTypeConstructor
topType: reflect.runtime.universe.Type = MyCaseClass
//As Before
val primaryParams = topType.typeSymbol.asClass.primaryConstructor...
primaryParams: List[reflect.runtime.universe.Symbol] = List(value elem,
value other)
primaryParams.map(_.typeSignature)
res29: List[reflect.runtime.universe.Type] = List(T, scala.Seq[U])
Inspecting the Type
topType.decls.foreach{case s => println(s.toString + "t" + s.typeSignature) }
value elem => T
value elem T
value other => scala.Seq[U]
value other scala.Seq[U]
constructor MyCaseClass (elem: T, other: scala.Seq[U])MyCaseClass[T,U]
method copy [T, U](elem: T, other: scala.Seq[U])MyCaseClass[T,U]
method copy$default$1 [T, U]=> T @scala.annotation.unchecked.uncheckedVariance
method copy$default$2 [T, U]=> scala.Seq[U] @scala.annotation.unchecked.uncheckedVariance
method productPrefix => java.lang.String
method productArity => scala.Int
method productElement (x$1: scala.Int)scala.Any
method productIterator => Iterator[scala.Any]
method canEqual (x$1: scala.Any)scala.Boolean
method hashCode ()scala.Int
method toString ()java.lang.String
method equals (x$1: scala.Any)scala.Boolean
val instanceMirror = cm.reflect(v)
instanceMirror: reflect.runtime.universe.InstanceMirror = instance
mirror for MyCaseClass(foo,(1))
val elemField=topType.decls.filterNot(x => x.isMethod).head
elemField: reflect.runtime.universe.Symbol = value elem
val elemValue=instanceMirror.reflectField(elemField.asTerm).get
elemValue: Any = foo
val elemTyp=cm.reflect(elemValue).symbol.toTypeConstructor
elemTyp: reflect.runtime.universe.Type = java.lang.String
Similarly for second param other: Seq[U]
val otherTyp= cm.reflect(otherValue).symbol.toTypeConstructor
otherTyp: reflect.runtime.universe.Type = OneIntSeq
val asBase=otherTyp.baseType(otherField.typeSignature.typeSymbol)
asBase: reflect.runtime.universe.Type = Seq[scala.Int]
val uType = asBase.typeArgs.head
uType: reflect.runtime.universe.Type = scala.Int
Combining Things together
val finalType=appliedType(topType,List(elemTyp,uType))
finalType: reflect.runtime.universe.Type =
MyCaseClass[java.lang.String,scala.Int]
Q.E.D
Final Thoughts
Questions?
Like pushing Scala to it’s limits? Thrive on
scalable computing with machine learning on
top?
Join us!

More Related Content

What's hot

Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Scala
ScalaScala
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Scala Intro
Scala IntroScala Intro
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
scala
scalascala
scala
Pranav E K
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
Hiroshi Ono
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
Derek Chen-Becker
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
Jakub Kahovec
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
Venkata Naga Ravi
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 

What's hot (18)

Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala
ScalaScala
Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
scala
scalascala
scala
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 

Viewers also liked

Scala reflection
Scala reflectionScala reflection
Scala reflection
David Pichsenmeister
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
Rose Toomey
 
Scaladoc for reflection
Scaladoc for reflectionScaladoc for reflection
Scaladoc for reflection
Vlad Ureche
 
Tools for Meta-Programming
Tools for Meta-ProgrammingTools for Meta-Programming
Tools for Meta-Programming
elliando dias
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
Abdelmonaim Remani
 
Spark Summit EU talk by Stavros kontopoulos and Justin Pihony
Spark Summit EU talk by Stavros kontopoulos and Justin PihonySpark Summit EU talk by Stavros kontopoulos and Justin Pihony
Spark Summit EU talk by Stavros kontopoulos and Justin Pihony
Spark Summit
 
Annotations
AnnotationsAnnotations
Annotations
Knoldus Inc.
 
Spark Summit EU talk by Luca Canali
Spark Summit EU talk by Luca CanaliSpark Summit EU talk by Luca Canali
Spark Summit EU talk by Luca Canali
Spark Summit
 
Akka Cluster and Auto-scaling
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scaling
Ikuo Matsumura
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineering
univalence
 
Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -
Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -
Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -
Yoshiyasu SAEKI
 
Optimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL JoinsOptimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL Joins
Databricks
 

Viewers also liked (12)

Scala reflection
Scala reflectionScala reflection
Scala reflection
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Scaladoc for reflection
Scaladoc for reflectionScaladoc for reflection
Scaladoc for reflection
 
Tools for Meta-Programming
Tools for Meta-ProgrammingTools for Meta-Programming
Tools for Meta-Programming
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Spark Summit EU talk by Stavros kontopoulos and Justin Pihony
Spark Summit EU talk by Stavros kontopoulos and Justin PihonySpark Summit EU talk by Stavros kontopoulos and Justin Pihony
Spark Summit EU talk by Stavros kontopoulos and Justin Pihony
 
Annotations
AnnotationsAnnotations
Annotations
 
Spark Summit EU talk by Luca Canali
Spark Summit EU talk by Luca CanaliSpark Summit EU talk by Luca Canali
Spark Summit EU talk by Luca Canali
 
Akka Cluster and Auto-scaling
Akka Cluster and Auto-scalingAkka Cluster and Auto-scaling
Akka Cluster and Auto-scaling
 
7 key recipes for data engineering
7 key recipes for data engineering7 key recipes for data engineering
7 key recipes for data engineering
 
Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -
Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -
Apache Sparkにおけるメモリ - アプリケーションを落とさないメモリ設計手法 -
 
Optimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL JoinsOptimizing Apache Spark SQL Joins
Optimizing Apache Spark SQL Joins
 

Similar to Scala Reflection & Runtime MetaProgramming

Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
e-Legion
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
Vasil Remeniuk
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
Felipe
 
Scala ntnu
Scala ntnuScala ntnu
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Hello scala
Hello scalaHello scala
Hello scala
Jinliang Ou
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
jeykottalam
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Raúl Raja Martínez
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
Shine Xavier
 
Scala active record
Scala active recordScala active record
Scala active record
鉄平 土佐
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
felixtrepanier
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
Skills Matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
Maciej Matyjas
 

Similar to Scala Reflection & Runtime MetaProgramming (20)

Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
 
scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Hello scala
Hello scalaHello scala
Hello scala
 
Intro to Spark and Spark SQL
Intro to Spark and Spark SQLIntro to Spark and Spark SQL
Intro to Spark and Spark SQL
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
Scala active record
Scala active recordScala active record
Scala active record
 
Intro to functional programming - Confoo
Intro to functional programming - ConfooIntro to functional programming - Confoo
Intro to functional programming - Confoo
 
Akka lsug skills matter
Akka lsug skills matterAkka lsug skills matter
Akka lsug skills matter
 
Scaling Web Apps with Akka
Scaling Web Apps with AkkaScaling Web Apps with Akka
Scaling Web Apps with Akka
 

Recently uploaded

VEMC: Trusted Leader in Engineering Solutions
VEMC: Trusted Leader in Engineering SolutionsVEMC: Trusted Leader in Engineering Solutions
VEMC: Trusted Leader in Engineering Solutions
VijayEngineeringandM1
 
Sea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy ResourcesSea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy Resources
21h16charis
 
Bell Crank Lever.pptxDesign of Bell Crank Lever
Bell Crank Lever.pptxDesign of Bell Crank LeverBell Crank Lever.pptxDesign of Bell Crank Lever
Bell Crank Lever.pptxDesign of Bell Crank Lever
ssuser110cda
 
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
IJAEMSJORNAL
 
Gen AI with LLM for construction technology
Gen AI with LLM for construction technologyGen AI with LLM for construction technology
Gen AI with LLM for construction technology
Tae wook kang
 
sensor networks unit wise 4 ppt units ppt
sensor networks unit wise 4  ppt units pptsensor networks unit wise 4  ppt units ppt
sensor networks unit wise 4 ppt units ppt
sarikasatya
 
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
Kiran Kumar Manigam
 
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
RanjanKumarPATEL4
 
Predicting damage in notched functionally graded materials plates thr...
Predicting  damage  in  notched  functionally  graded  materials  plates  thr...Predicting  damage  in  notched  functionally  graded  materials  plates  thr...
Predicting damage in notched functionally graded materials plates thr...
Barhm Mohamad
 
Cyber security detailed ppt and understand
Cyber security detailed ppt and understandCyber security detailed ppt and understand
Cyber security detailed ppt and understand
docpain605501
 
software engineering software engineering
software engineering software engineeringsoftware engineering software engineering
software engineering software engineering
PrabhuB33
 
System Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th editionSystem Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th edition
mnassar75g
 
Structural Dynamics and Earthquake Engineering
Structural Dynamics and Earthquake EngineeringStructural Dynamics and Earthquake Engineering
Structural Dynamics and Earthquake Engineering
tushardatta
 
THERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantagesTHERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantages
VikramSingh6251
 
HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.
HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.
HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.
NoeAranel
 
,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي
,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي
,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي
nafizanafzal
 
Aiml ppt pdf.pdf on music recommendation system
Aiml ppt pdf.pdf on music recommendation systemAiml ppt pdf.pdf on music recommendation system
Aiml ppt pdf.pdf on music recommendation system
UdhavGupta6
 
Introduction to Course_1 for Cyber Security
Introduction to Course_1 for Cyber SecurityIntroduction to Course_1 for Cyber Security
Introduction to Course_1 for Cyber Security
kuldeephule1989
 
02 - Method Statement for Concrete pouring.docx
02 - Method Statement for Concrete pouring.docx02 - Method Statement for Concrete pouring.docx
02 - Method Statement for Concrete pouring.docx
RAHEEL KHALID
 
Database management system module -3 bcs403
Database management system module -3 bcs403Database management system module -3 bcs403
Database management system module -3 bcs403
Tharani4825
 

Recently uploaded (20)

VEMC: Trusted Leader in Engineering Solutions
VEMC: Trusted Leader in Engineering SolutionsVEMC: Trusted Leader in Engineering Solutions
VEMC: Trusted Leader in Engineering Solutions
 
Sea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy ResourcesSea Wave Energy - Renewable Energy Resources
Sea Wave Energy - Renewable Energy Resources
 
Bell Crank Lever.pptxDesign of Bell Crank Lever
Bell Crank Lever.pptxDesign of Bell Crank LeverBell Crank Lever.pptxDesign of Bell Crank Lever
Bell Crank Lever.pptxDesign of Bell Crank Lever
 
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
Agricultural Profitability through Resilience: Smallholder Farmers' Strategie...
 
Gen AI with LLM for construction technology
Gen AI with LLM for construction technologyGen AI with LLM for construction technology
Gen AI with LLM for construction technology
 
sensor networks unit wise 4 ppt units ppt
sensor networks unit wise 4  ppt units pptsensor networks unit wise 4  ppt units ppt
sensor networks unit wise 4 ppt units ppt
 
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
RAILWAYS, a vital part of our infrastructure, play a crucial role in ensuring...
 
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
414565650-Mixing-and-Agglomeration-in-Eirich-Mixers.pdf
 
Predicting damage in notched functionally graded materials plates thr...
Predicting  damage  in  notched  functionally  graded  materials  plates  thr...Predicting  damage  in  notched  functionally  graded  materials  plates  thr...
Predicting damage in notched functionally graded materials plates thr...
 
Cyber security detailed ppt and understand
Cyber security detailed ppt and understandCyber security detailed ppt and understand
Cyber security detailed ppt and understand
 
software engineering software engineering
software engineering software engineeringsoftware engineering software engineering
software engineering software engineering
 
System Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th editionSystem Analysis and Design in a changing world 5th edition
System Analysis and Design in a changing world 5th edition
 
Structural Dynamics and Earthquake Engineering
Structural Dynamics and Earthquake EngineeringStructural Dynamics and Earthquake Engineering
Structural Dynamics and Earthquake Engineering
 
THERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantagesTHERMAL POWER PLANT its applications and advantages
THERMAL POWER PLANT its applications and advantages
 
HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.
HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.
HSE-BMS-009 COSHH & MSDS.pptHSE-BMS-009 COSHH & MSDS.pptSE-BMS-009 COSHH & MSDS.
 
,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي
,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي
,*$/?!~00971508021841^(سعر حبوب الإجهاض في دبي
 
Aiml ppt pdf.pdf on music recommendation system
Aiml ppt pdf.pdf on music recommendation systemAiml ppt pdf.pdf on music recommendation system
Aiml ppt pdf.pdf on music recommendation system
 
Introduction to Course_1 for Cyber Security
Introduction to Course_1 for Cyber SecurityIntroduction to Course_1 for Cyber Security
Introduction to Course_1 for Cyber Security
 
02 - Method Statement for Concrete pouring.docx
02 - Method Statement for Concrete pouring.docx02 - Method Statement for Concrete pouring.docx
02 - Method Statement for Concrete pouring.docx
 
Database management system module -3 bcs403
Database management system module -3 bcs403Database management system module -3 bcs403
Database management system module -3 bcs403
 

Scala Reflection & Runtime MetaProgramming

  • 2. About Me Meir Maor Chief Architect @ SparkBeyond At SparkBeyond we leverage the collective human knowledge to solve the world's toughest problems
  • 3. This Talk Showcase Scala reflection, and compiler toolbox Use a real guiding example to see how these are used to solve a real problem
  • 4. SparkBeyond SparkBeyond generates code to solve machine learning problems, leveraging world knowledge Allows crafting deeply embedded pipelines to explicitly transform your data
  • 5. Guiding Example ● We would like to build a deeply embedded framework to transform data. ● Multiple classes define actions ● Can be stacked together ● Embed user generated Scala code ● Auto generate a UI to input parameters for actions. ● Allow annotating fields to guide UI generation
  • 6. case class AddColumn(columnName: String,codeExpression: String) extends Action {...} case class SpecialParam(a: Int,b : Int => Int) object SpecialAction { val myMap = Map("mul2" -> SpecialParam(1,_ * 2), "add1" -> SpecialParam(2,_ + 1), "ident" -> SpecialParam(3, identity) ) } case class SpecialAction(@PossibleValuesMap(SpecialAction.myMap) foo: SpecialParam) extends Action
  • 7. Intro to Scala Meta Programming Creating and using mirror import reflect.runtime.universe._ val cm = runtimeMirror(getClass.getClassLoader)
  • 8. Know the players ● Type ● Symbol ● Tree documentation reference: http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html
  • 9. Type val t=typeOf[List[Int]] t: reflect.runtime.universe.Type = scala.List[Int] Compare with =:= or <:< or weak_<:< Key methods: declarations, baseClasses, BaseType, typeSymbol
  • 10. Symbol ● If it has a name it has a Symbol – Types, Members, parameters Not a type, even TypeSymbol is less than a Type val ts=t.typeSymbol ts: reflect.runtime.universe.Symbol = class List
  • 11. Tree ● An Abstract Syntax Tree val tree = Apply(Select(Ident(TermName("x")), TermName("$plus")), List(Literal(Constant(2)))) tree: scala.reflect.runtime.universe.Apply = x.$plus(2) val expr = reify { class Flower { def name = "Rose" } } expr: scala.reflect.runtime.universe.Expr[Unit] = … expr.tree
  • 12. Get param list from primary ctr scala> val typ = typeOf[AddColumn] typ: reflect.runtime.universe.Type = AddColumn val primary=typ.typeSymbol.asClass.primaryConstructor primary: reflect.runtime.universe.Symbol = constructor AddColumn //recall a method can have multiple param lists, hence flaten val paramList = primary.asMethod.paramLists.flatten paramList: List[reflect.runtime.universe.Symbol] = List(value columnName, value codeExpression)
  • 13. Code Generation ● Cglib – byte code generation library ● Compiling externally and loading with a fresh classloader ● The unsafe way - mutate the existing classloader ● Scala Compiler toolbox
  • 14. UrlClassLoader def getClassInstanceFromJar[T](jarFile: File, className: String): T = { val classLoader = new scala.reflect.internal.util.ScalaClassLoader.URLClassLoader(Seq(ja rFile.toURI.toURL), this.getClass.getClassLoader) val mirror = scala.reflect.runtime.universe.runtimeMirror(classLoader) val classSymbol = mirror.staticClass(className) val ctorSymbol = classSymbol.primaryConstructor.asMethod val ctor = mirror.reflectClass(classSymbol).reflectConstructor(ctorSymbol) ctor.apply().asInstanceOf[T] }
  • 15. Mutate existing ClassLoader public static void addURL(URL u) throws IOException { URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { Method method = sysclass.getDeclaredMethod("addURL", parameters); method.setAccessible(true); method.invoke(sysloader, new Object[]{u}); } catch (Throwable t) { t.printStackTrace(); throw new IOException("Error, could not add URL to system classloader"); }//end try catch }//end method
  • 16. Compiler ToolBox ● Experimental (even more so than the rest of the reflection api) import scala.tools.reflect.ToolBox val tb = cm.mkToolBox() ● Parse, typecheck, eval def run(code: String) = { synchronized { val tree = tb parse s"import scala._nimport Predef._n $code" tb eval tree } }
  • 17. Using the ToolBox ● Get User code fragment ● Add boilerplate function definition, useful variables ● Parse and eval ● Apply function on new data
  • 18. Annotations ● In Java you can easily read annotations reflectively at runtime ● Annotations can only hold specific types: – primitive – String – Class – an Enum – another Annotation – an array of any of the above
  • 19. Scala annotations ● Scala annotations are not Java annotations ● You can put anything in a Scala annotation ● But How do you read it? Documentation: http://docs.scala-lang.org/overviews/reflection/annotations-names-scopes.html
  • 20. Defining Scala Annotation Extend StaticAnnotation to make it available at Runtime case class ValuesMap(vals: Map[String, Any]) extends StaticAnnotation
  • 21. Get annotations from a symbol ● Many things can be annotated – A type, A Method, A parameter, a val/var ● Recall our example: case class SpecialAction(@ValuesMap(SpecialAction.myMap) foo: SpecialParam) extends Action
  • 22. Get annotations from a symbol val param: Symbol = longestParmList.head param: reflect.runtime.universe.Symbol = value foo val annotations = param.annotations scala> annotations: List[reflect.runtime.universe.Annotation] = List(com.sparkbeyond.runtime.util.misc.ValuesMap(SpecialAction.m yMap)
  • 23. Recreate Annotation Instance scala> val tree=annotations.head.tree tree: reflect.runtime.universe.Tree = new com.sparkbeyond.runtime.util.misc.ValuesMap(SpecialAction.myMap) scala> tb.eval(tb.untypecheck(tree)) res15: Any = ValuesMap(Map(mul2 -> SpecialParam(1,<function1>), add1 -> SpecialParam(2,<function1>), ident -> SpecialParam(3,<function1>)))
  • 24. Overcoming Erasure - RTTI ● Java Generics for better or worse get erased in runtime ● We would like to be able to tell the Type of an instance including Type Parameters ● In most cases this is possible in a meaningful way.
  • 25. What is my type? case class OneIntSeq(a: Int) extends Seq[Int] {...} case class MyCaseClass[T,U](e: T,o: Seq[U]) val v = MyCaseClass("foo",OneIntSeq(1)) We want a method, given v to produce: MyCaseClass[String,Int]
  • 26. val topType=cm.reflect(v).symbol.toTypeConstructor topType: reflect.runtime.universe.Type = MyCaseClass //As Before val primaryParams = topType.typeSymbol.asClass.primaryConstructor... primaryParams: List[reflect.runtime.universe.Symbol] = List(value elem, value other) primaryParams.map(_.typeSignature) res29: List[reflect.runtime.universe.Type] = List(T, scala.Seq[U])
  • 27. Inspecting the Type topType.decls.foreach{case s => println(s.toString + "t" + s.typeSignature) } value elem => T value elem T value other => scala.Seq[U] value other scala.Seq[U] constructor MyCaseClass (elem: T, other: scala.Seq[U])MyCaseClass[T,U] method copy [T, U](elem: T, other: scala.Seq[U])MyCaseClass[T,U] method copy$default$1 [T, U]=> T @scala.annotation.unchecked.uncheckedVariance method copy$default$2 [T, U]=> scala.Seq[U] @scala.annotation.unchecked.uncheckedVariance method productPrefix => java.lang.String method productArity => scala.Int method productElement (x$1: scala.Int)scala.Any method productIterator => Iterator[scala.Any] method canEqual (x$1: scala.Any)scala.Boolean method hashCode ()scala.Int method toString ()java.lang.String method equals (x$1: scala.Any)scala.Boolean
  • 28. val instanceMirror = cm.reflect(v) instanceMirror: reflect.runtime.universe.InstanceMirror = instance mirror for MyCaseClass(foo,(1)) val elemField=topType.decls.filterNot(x => x.isMethod).head elemField: reflect.runtime.universe.Symbol = value elem val elemValue=instanceMirror.reflectField(elemField.asTerm).get elemValue: Any = foo val elemTyp=cm.reflect(elemValue).symbol.toTypeConstructor elemTyp: reflect.runtime.universe.Type = java.lang.String
  • 29. Similarly for second param other: Seq[U] val otherTyp= cm.reflect(otherValue).symbol.toTypeConstructor otherTyp: reflect.runtime.universe.Type = OneIntSeq val asBase=otherTyp.baseType(otherField.typeSignature.typeSymbol) asBase: reflect.runtime.universe.Type = Seq[scala.Int] val uType = asBase.typeArgs.head uType: reflect.runtime.universe.Type = scala.Int
  • 30. Combining Things together val finalType=appliedType(topType,List(elemTyp,uType)) finalType: reflect.runtime.universe.Type = MyCaseClass[java.lang.String,scala.Int] Q.E.D
  • 31. Final Thoughts Questions? Like pushing Scala to it’s limits? Thrive on scalable computing with machine learning on top? Join us!