SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
Metaprogramming in Scala 2.10


        Eugene Burmako

          EPFL, LAMP



         28 April 2012
Agenda

  Intro

  Reflection

  Universes

  Demo

  Macros

  Summary
Metaprogramming




     Metaprogramming is the writing of computer programs
     that write or manipulate other programs or themselves as
     their data.
                                                     —Wikipedia
Compiler




   Q: How to enable metaprogramming?
   A: Who has more data about a program than a compiler?
   Let’s expose the compiler to the programmer.
Reflection




   In 2.10 we expose data about programs via reflection API.
   The API is spread between scala-library.jar (interfaces),
   scala-reflect.jar (implementations) and scala-compiler.jar
   (runtime compilation).
Martin knows better




   Design of the reflection API is explained in great detail in a recent
   talk by Martin Odersky:
   channel9.msdn.com/Lang-NEXT-2012/Reflection-and-Compilers
Hands on




  Today we will learn the fundamentals of reflection API and learn to
  learn more about it via a series of hands-on examples.
Macros



  Q: Hey! What about macros?
  A: Reflection is at the core of macros, reflection provides macros
  with an API, reflection enables macros. Our focus today is
  understanding reflection, macros are just a tiny bolt-on.
  For more information about macros,
  their philosophy and applications, take a look at my Scala Days talk:
  http://scalamacros.org/talks/2012-04-18-ScalaDays2012.pdf.
Agenda

  Intro

  Reflection

  Universes

  Demo

  Macros

  Summary
Core data structures

       Trees
       Symbols
       Types
   C:ProjectsKepler>scalac -Xshow-phases
   phase name id description
   ---------- -- -----------
       parser 1 parse source into ASTs, simple desugaring
        namer 2 resolve names, attach symbols to named trees
        typer 4 the meat and potatoes: type the trees
      pickler 7 serialize symbol tables


   I’ll do my best to explain these concepts, but it’s barely possible to
   do it better than Paul Phillips. Be absolutely sure to watch the
   Inside the Sausage Factory talk (when the video is up).
Trees




   Short-lived, mostly immutable, mostly plain case classes.
   Apply(Ident("println"), List(Literal(Constant("hi!"))))


   Comprehensive list of public trees can be found here:
   scala/reflect/api/Trees.scala (be sure to take a look at the
   ”standard pattern match” section in the end of the file).
Learn to learn



       -Xprint:parser (for naked trees)
       -Xprint:typer (for typechecked trees)
       -Yshow-trees and its cousins
       scala.reflect.mirror.showRaw(scala.reflect.mirror.reify(...))
   Q: Where do I pull these compiler flags from?
   A: scala/tools/nsc/settings/ScalaSettings.scala
-Yshow-trees
   // also try -Yshow-trees-stringified
   // and -Yshow-trees-compact (or both simultaneously)
   >scalac -Xprint:parser -Yshow-trees HelloWorld.scala
   [[syntax trees at end of parser]]// Scala source:
       HelloWorld.scala
   PackageDef(
     "<empty>"
     ModuleDef(
       0
       "Test"
       Template(
         "App" // parents
         ValDef(
           private
           "_"
           <tpt>
           <empty>
         )
         ...
showRaw
  scala> scala.reflect.mirror.reify{object Test {
    println("Hello World!")
  }}
  res0: reflect.mirror.Expr[Unit] = ...

  scala> scala.reflect.mirror.showRaw(res0.tree)
  res1: String = Block(List(ModuleDef(
    Modifiers(),
    newTermName("Test"),
    Template(List(Ident(newTypeName("Object"))), List(
      DefDef(Modifiers(), newTermName("<init>"), List(),
          List(List()), TypeTree(),
          Block(List(Apply(Select(Super(This(newTypeName("")),
          newTypeName("")), newTermName("<init>")),
          List())), Literal(Constant(())))),
      Apply(Select(Select(This(newTypeName("scala")),
          newTermName("Predef")), newTermName("println")),
          List(Literal(Constant("Hello World!")))))))),
  Literal(Constant(())))
Symbols
  Link definitions and references to definitions. Long-lived, mutable.
  Declared in scala/reflect/api/Symbols.scala (very much in flux
  right now!)
  def foo[T: TypeTag](x: Any) = x.asInstanceOf[T]
  foo[Long](42)


  foo, T, x introduce symbols (T actually produces two different
  symbols). DefDef, TypeDef, ValDef - all of those subtype
  DefTree.
  TypeTag, x, T, foo, Long refer to symbols. They are all
  represented by Idents, which subtype RefTree.
  Symbols are long-lived. This means that any reference to Int (from
  a tree or from a type) will point to the same symbol
  instance.
Learn to learn



       -Xprint:namer or -Xprint:typer
       -uniqid
       symbol.kind and -Yshow-symkinds
       :type -v
       Don’t create them by yourself. Just don’t, leave it to Namer.
       In macros most of the time you create naked trees, and Typer
       will take care of the rest.
-uniqid and -Yshow-symkinds
   >cat Foo.scala
   def foo[T: TypeTag](x: Any) = x.asInstanceOf[T]
   foo[Long](42)

   // there is a mysterious factoid hidden in this printout!
   >scalac -Xprint:typer -uniqid -Yshow-symkinds Foo.scala
   [[syntax trees at end of typer]]// Scala source: Foo.scala
   def foo#8339#METH
     [T#8340#TPE >: Nothing#4658#CLS <: Any#4657#CLS]
     (x#9529#VAL: Any#4657#CLS)
     (implicit evidence$1#9530#VAL:
         TypeTag#7861#TPE[T#8341#TPE#SKO])
     : T#8340#TPE =
     x#9529#VAL.asInstanceOf#6023#METH[T#8341#TPE#SKO];

   Test#14#MODC.this.foo#8339#METH[Long#1641#CLS](42)
   (scala#29#PK.reflect#2514#PK.‘package‘#3414#PKO
   .mirror#3463#GET.TypeTag#10351#MOD.Long#10361#GET)
:type -v




   We have just seen how to discover symbols used in trees.
   However, symbols are also used in types.
   Thanks to Paul (who hacked this during one of Scala Nights)
   there’s an easy way to inspect types as well. Corresponding REPL
   incantation is shown on one of the next slides.
Types




  Immutable, long-lived, sometimes cached case classes declared in
  scala/reflect/api/Types.scala.
  Store the information about the full wealth of the Scala type
  system: members, type arguments, higher kinds, path
  dependencies, erasures, etc.
Learn to learn




       -Xprint:typer
       -Xprint-types
       :type -v
       -explaintypes
-Xprint-types




   -Xprint-types is yet another option that modifies tree printing.
   Nothing very fancy, let’s move on to something really cool.
:type -v
   scala> :type -v def impl[T: c.TypeTag](c: Context) = ???
   // Type signature
   [T](c: scala.reflect.makro.Context)(implicit evidence$1:
       c.TypeTag[T])Nothing

   // Internal Type structure
   PolyType(
     typeParams = List(TypeParam(T))
     resultType = MethodType(
       params = List(TermSymbol(c: ...))
       resultType = MethodType(
         params = List(TermSymbol(implicit evidence$1: ...))
         resultType = TypeRef(
           TypeSymbol(final abstract class Nothing)
         )
       )
     )
   )
-explaintypes
   >cat Test.scala
   class Foo { class Bar; def bar(x: Bar) = ??? }

   object Test extends App {
     val foo1 = new Foo
     val foo2 = new Foo
     foo2.bar(new foo1.Bar)
   }

   // prints explanations of type mismatches
   >scalac -explaintypes Test.scala
   Test.foo1.Bar <: Test.foo2.Bar?
     Test.foo1.type <: Test.foo2.type?
       Test.foo1.type = Test.foo2.type?
       false
     false
   false
   Test.scala:6: error: type mismatch;
   ...
Big picture

       Trees are created naked by Parser.
       Both definitions and references (expressed as ASTs) get their
       symbols filled in by Namer (tree.symbol).
       When creating symbols, Namer also creates their completers,
       lazy thunks that know how to populate symbol types
       (symbol.info).
       Typer inspects trees, uses their symbols to transform trees
       and assign types to them (tree.tpe).
       Shortly afterwards Pickler kicks in and serializes reachable
       symbols along with their types into ScalaSignature
       annotations.
Agenda

  Intro

  Reflection

  Universes

  Demo

  Macros

  Summary
Universes




   Universes are environments that pack together trees, symbols and
   their types.
       Compiler (scala.tools.nsc.Global) is a universe.
       Reflective mirror (scala.reflect.mirror) is a universe too.
       Macro context (scala.reflect.makro.Context) holds a reference
       to a universe.
Symbol tables




   Universes abstract population of symbol tables.
       Compiler loads symbols from pickles using its own *.class
       parser.
       Reflective mirror uses Java reflection to load and parse
       ScalaSignatures.
       Macro context refers to the compiler’s symbol table.
Entry points



   Using a universe depends on your scenario.
       You can play with compiler’s universe (aka global) in REPL’s
       :power mode.
       With mirrors you go through the Mirror interface, e.g.
       symbolOfInstance or classToType.
       In a macro context, you import c.mirror. and can use
       imported factories to create trees and types (don’t create
       symbols manually, remember?).
Path dependency

  An important quirk is that all universe artifacts are path-dependent
  on their universe. Note the ”reflect.mirror” prefix in the type of
  the result printed below.
  scala> scala.reflect.mirror.reify(2.toString)
  res0: reflect.mirror.Expr[String] =
      Expr[String](2.toString())


  When you deal with runtime reflection, you simply import
  scala.reflect.mirror. , and enjoy, because typically there is only one
  runtime mirror.
  However with macros it’s more complicated. To pass artifacts
  around (e.g. into helper functions), you need to also carry the
  universe with you. Or you can employ the technique outlined in
  a discussion at scala-internals.
Agenda

  Intro

  Reflection

  Universes

  Demo

  Macros

  Summary
Inspect members
   scala> import scala.reflect.mirror
   import scala.reflect.mirror

   scala> trait X { def foo: String }
   defined trait X

   scala> typeTag[X]
   res1: TypeTag[X] = ConcreteTypeTag[X]

   scala> res1.tpe.members
   res2: Iterable[reflect.mirror.Symbol] = List(method
       $asInstanceOf, method $isInstanceOf, method sync
   hronized, method ##, method !=, method ==, method ne,
       method eq, constructor Object, method notifyAl
   l, method notify, method clone, method getClass, method
       hashCode, method toString, method equals, me
   thod wait, method wait, method wait, method finalize,
       method asInstanceOf, method isInstanceOf, meth
   od !=, method ==, method foo)
Analyze, typecheck and invoke members
   val d = new DynamicProxy{ val dynamicProxyTarget = x }
   d.noargs
   d.noargs()
   d.nullary
   d.value
   d.-
   d.$("x")
   d.overloaded("overloaded with object")
   d.overloaded(1)
   val car = new Car
   d.typeArgs(car) // inferred
   d.default(1, 3)
   d.default(1)
   d.named(1, c=3, b=2) // works, wow


   The proxy uses reflection that is capable of resolving all these calls.
   More examples at test/files/run/dynamic-proxy.scala.
   Implementation is at scala/reflect/DynamicProxy.scala.
Defeat erasure

   scala> def foo[T](x: T) = x.getClass
   foo: [T](x: T)Class[_ <: T]

   scala> foo(List(1, 2, 3))
   res0: Class[_ <: List[Int]] = class
       scala.collection.immutable.$colon$colon

   scala> def foo[T: TypeTag](x: T) = typeTag[T]
   foo: [T](x: T)(implicit evidence$1: TypeTag[T])TypeTag[T]

   scala> foo(List(1, 2, 3))
   res1: TypeTag[List[Int]] = ConcreteTypeTag[List[Int]]

   scala> res1.tpe
   res2: reflect.mirror.Type = List[Int]
Compile at runtime


   import scala.reflect.mirror._
   val tree = Apply(Select(Ident("Macros"),
       newTermName("foo")), List(Literal(Constant(42))))
   println(Expr(tree).eval)


   Eval creates a toolbox under the covers (universe.mkToolBox),
   which is a full-fledged compiler.
   Toolbox wraps the input AST, sets its phase to Namer (skipping
   Parser) and performs the compilation into an in-memory
   directory.
   After the compilation is finished, toolbox fires up a classloader that
   loads and lauches the code.
Agenda

  Intro

  Reflection

  Universes

  Demo

  Macros

  Summary
Macros


  In our hackings above, we used the runtime mirror
  (scala.reflect.mirror) to reflect against program structure.
  We can do absolutely the same during the compile time. The
  universe is already there (the compiler itself), the API is there as
  well (scala.reflect.api.Universe inside the macro context).
  We only need to ask the compiler to call ourselves during the
  compilation (currently, our trigger is macro application and the
  hook is the macro keyword).
  The end.
No, really




   That’s it.
Agenda

  Intro

  Reflection

  Universes

  Demo

  Macros

  Summary
Summary




     In 2.10 you can have all the information about your program
     that the compiler has (well, almost).
     This information includes trees, symbols and types. And
     annotations. And positions. And more.
     You can reflect at runtime (scala.reflect.mirror) or at
     compile-time (macros).
Status




   We’re already there.
   Recently released 2.10.0-M3 includes reflection and macros.
Thanks!




          eugene.burmako@epfl.ch

Weitere ähnliche Inhalte

Was ist angesagt?

A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
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 ScalaDerek Chen-Becker
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: NotesRoberto Casadei
 
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 2010Derek Chen-Becker
 

Was ist angesagt? (20)

Scala Intro
Scala IntroScala Intro
Scala Intro
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
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
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Scala
ScalaScala
Scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
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
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
scala
scalascala
scala
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 

Andere mochten auch

Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascadingjohnynek
 
Scala in practice
Scala in practiceScala in practice
Scala in practiceTomer Gabel
 
BigData, Hadoop과 Node.js, R2
BigData, Hadoop과 Node.js, R2BigData, Hadoop과 Node.js, R2
BigData, Hadoop과 Node.js, R2고포릿 default
 
Elixirと他言語の比較的紹介 ver.2
Elixirと他言語の比較的紹介ver.2Elixirと他言語の比較的紹介ver.2
Elixirと他言語の比較的紹介 ver.2Tsunenori Oohara
 
Go言語によるwebアプリの作り方
Go言語によるwebアプリの作り方Go言語によるwebアプリの作り方
Go言語によるwebアプリの作り方Yasutaka Kawamoto
 
PHP7はなぜ速いのか
PHP7はなぜ速いのかPHP7はなぜ速いのか
PHP7はなぜ速いのかYoshio Hanawa
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰Sungchul Park
 
地獄のElixir(目黒スタートアップ勉強会)
地獄のElixir(目黒スタートアップ勉強会)地獄のElixir(目黒スタートアップ勉強会)
地獄のElixir(目黒スタートアップ勉強会)Tsunenori Oohara
 
PHP7で変わること ——言語仕様とエンジンの改善ポイント
PHP7で変わること ——言語仕様とエンジンの改善ポイントPHP7で変わること ——言語仕様とエンジンの改善ポイント
PHP7で変わること ——言語仕様とエンジンの改善ポイントYoshio Hanawa
 
Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)
Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)
Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)NTT DATA OSS Professional Services
 
Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)
Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)
Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)NTT DATA OSS Professional Services
 
GoによるWebアプリ開発のキホン
GoによるWebアプリ開発のキホンGoによるWebアプリ開発のキホン
GoによるWebアプリ開発のキホンAkihiko Horiuchi
 

Andere mochten auch (15)

Scala profiling
Scala profilingScala profiling
Scala profiling
 
Scalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/CascadingScalding: Twitter's Scala DSL for Hadoop/Cascading
Scalding: Twitter's Scala DSL for Hadoop/Cascading
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
BigData, Hadoop과 Node.js, R2
BigData, Hadoop과 Node.js, R2BigData, Hadoop과 Node.js, R2
BigData, Hadoop과 Node.js, R2
 
Scala reflection
Scala reflectionScala reflection
Scala reflection
 
RESTful Java
RESTful JavaRESTful Java
RESTful Java
 
Elixirと他言語の比較的紹介 ver.2
Elixirと他言語の比較的紹介ver.2Elixirと他言語の比較的紹介ver.2
Elixirと他言語の比較的紹介 ver.2
 
Go言語によるwebアプリの作り方
Go言語によるwebアプリの作り方Go言語によるwebアプリの作り方
Go言語によるwebアプリの作り方
 
PHP7はなぜ速いのか
PHP7はなぜ速いのかPHP7はなぜ速いのか
PHP7はなぜ速いのか
 
java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰java 8 람다식 소개와 의미 고찰
java 8 람다식 소개와 의미 고찰
 
地獄のElixir(目黒スタートアップ勉強会)
地獄のElixir(目黒スタートアップ勉強会)地獄のElixir(目黒スタートアップ勉強会)
地獄のElixir(目黒スタートアップ勉強会)
 
PHP7で変わること ——言語仕様とエンジンの改善ポイント
PHP7で変わること ——言語仕様とエンジンの改善ポイントPHP7で変わること ——言語仕様とエンジンの改善ポイント
PHP7で変わること ——言語仕様とエンジンの改善ポイント
 
Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)
Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)
Apache Spark超入門 (Hadoop / Spark Conference Japan 2016 講演資料)
 
Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)
Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)
Apache Sparkに手を出してヤケドしないための基本 ~「Apache Spark入門より」~ (デブサミ 2016 講演資料)
 
GoによるWebアプリ開発のキホン
GoによるWebアプリ開発のキホンGoによるWebアプリ開発のキホン
GoによるWebアプリ開発のキホン
 

Ähnlich wie Metaprogramming in Scala 2.10, Eugene Burmako,

scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene BurmakoVasil Remeniuk
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»e-Legion
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
Macros and reflection in scala 2.10
Macros and reflection in scala 2.10Macros and reflection in scala 2.10
Macros and reflection in scala 2.10Johan Andrén
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaScala Italy
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...Scala Italy
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data ManagementAlbert Bifet
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 

Ähnlich wie Metaprogramming in Scala 2.10, Eugene Burmako, (20)

scala.reflect, Eugene Burmako
scala.reflect, Eugene Burmakoscala.reflect, Eugene Burmako
scala.reflect, Eugene Burmako
 
Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»Евгений Бурмако «scala.reflect»
Евгений Бурмако «scala.reflect»
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Macros and reflection in scala 2.10
Macros and reflection in scala 2.10Macros and reflection in scala 2.10
Macros and reflection in scala 2.10
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Martin Odersky - Evolution of Scala
Martin Odersky - Evolution of ScalaMartin Odersky - Evolution of Scala
Martin Odersky - Evolution of Scala
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Devoxx
DevoxxDevoxx
Devoxx
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
Reflection in Scala Whats, Whys and Hows - Walter Cazzola (Dipartimento di In...
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Real Time Big Data Management
Real Time Big Data ManagementReal Time Big Data Management
Real Time Big Data Management
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 

Mehr von Vasil Remeniuk

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикVasil Remeniuk
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Vasil Remeniuk
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Vasil Remeniuk
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Vasil Remeniuk
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform researchVasil Remeniuk
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform ResearchVasil Remeniuk
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaVasil Remeniuk
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform ResearchVasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovVasil Remeniuk
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovVasil Remeniuk
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, PauliusVasil Remeniuk
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Vasil Remeniuk
 
Spark intro by Adform Research
Spark intro by Adform ResearchSpark intro by Adform Research
Spark intro by Adform ResearchVasil Remeniuk
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaVasil Remeniuk
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Vasil Remeniuk
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform ResearchVasil Remeniuk
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Vasil Remeniuk
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + ElkVasil Remeniuk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхVasil Remeniuk
 

Mehr von Vasil Remeniuk (20)

Product Minsk - РТБ и Программатик
Product Minsk - РТБ и ПрограмматикProduct Minsk - РТБ и Программатик
Product Minsk - РТБ и Программатик
 
Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14Работа с Akka Сluster, @afiskon, scalaby#14
Работа с Akka Сluster, @afiskon, scalaby#14
 
Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14Cake pattern. Presentation by Alex Famin at scalaby#14
Cake pattern. Presentation by Alex Famin at scalaby#14
 
Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3Scala laboratory: Globus. iteration #3
Scala laboratory: Globus. iteration #3
 
Testing in Scala by Adform research
Testing in Scala by Adform researchTesting in Scala by Adform research
Testing in Scala by Adform research
 
Spark Intro by Adform Research
Spark Intro by Adform ResearchSpark Intro by Adform Research
Spark Intro by Adform Research
 
Types by Adform Research, Saulius Valatka
Types by Adform Research, Saulius ValatkaTypes by Adform Research, Saulius Valatka
Types by Adform Research, Saulius Valatka
 
Types by Adform Research
Types by Adform ResearchTypes by Adform Research
Types by Adform Research
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Scalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex GryzlovScalding by Adform Research, Alex Gryzlov
Scalding by Adform Research, Alex Gryzlov
 
Spark by Adform Research, Paulius
Spark by Adform Research, PauliusSpark by Adform Research, Paulius
Spark by Adform Research, Paulius
 
Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)Scala Style by Adform Research (Saulius Valatka)
Scala Style by Adform Research (Saulius Valatka)
 
Spark intro by Adform Research
Spark intro by Adform ResearchSpark intro by Adform Research
Spark intro by Adform Research
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius Valatka
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
 
Testing in Scala. Adform Research
Testing in Scala. Adform ResearchTesting in Scala. Adform Research
Testing in Scala. Adform Research
 
Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1Scala laboratory. Globus. iteration #1
Scala laboratory. Globus. iteration #1
 
Cassandra + Spark + Elk
Cassandra + Spark + ElkCassandra + Spark + Elk
Cassandra + Spark + Elk
 
Опыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событияхОпыт использования Spark, Основано на реальных событиях
Опыт использования Spark, Основано на реальных событиях
 
ETL со Spark
ETL со SparkETL со Spark
ETL со Spark
 

Kürzlich hochgeladen

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 

Kürzlich hochgeladen (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 

Metaprogramming in Scala 2.10, Eugene Burmako,

  • 1. Metaprogramming in Scala 2.10 Eugene Burmako EPFL, LAMP 28 April 2012
  • 2. Agenda Intro Reflection Universes Demo Macros Summary
  • 3. Metaprogramming Metaprogramming is the writing of computer programs that write or manipulate other programs or themselves as their data. —Wikipedia
  • 4. Compiler Q: How to enable metaprogramming? A: Who has more data about a program than a compiler? Let’s expose the compiler to the programmer.
  • 5. Reflection In 2.10 we expose data about programs via reflection API. The API is spread between scala-library.jar (interfaces), scala-reflect.jar (implementations) and scala-compiler.jar (runtime compilation).
  • 6. Martin knows better Design of the reflection API is explained in great detail in a recent talk by Martin Odersky: channel9.msdn.com/Lang-NEXT-2012/Reflection-and-Compilers
  • 7. Hands on Today we will learn the fundamentals of reflection API and learn to learn more about it via a series of hands-on examples.
  • 8. Macros Q: Hey! What about macros? A: Reflection is at the core of macros, reflection provides macros with an API, reflection enables macros. Our focus today is understanding reflection, macros are just a tiny bolt-on. For more information about macros, their philosophy and applications, take a look at my Scala Days talk: http://scalamacros.org/talks/2012-04-18-ScalaDays2012.pdf.
  • 9. Agenda Intro Reflection Universes Demo Macros Summary
  • 10. Core data structures Trees Symbols Types C:ProjectsKepler>scalac -Xshow-phases phase name id description ---------- -- ----------- parser 1 parse source into ASTs, simple desugaring namer 2 resolve names, attach symbols to named trees typer 4 the meat and potatoes: type the trees pickler 7 serialize symbol tables I’ll do my best to explain these concepts, but it’s barely possible to do it better than Paul Phillips. Be absolutely sure to watch the Inside the Sausage Factory talk (when the video is up).
  • 11. Trees Short-lived, mostly immutable, mostly plain case classes. Apply(Ident("println"), List(Literal(Constant("hi!")))) Comprehensive list of public trees can be found here: scala/reflect/api/Trees.scala (be sure to take a look at the ”standard pattern match” section in the end of the file).
  • 12. Learn to learn -Xprint:parser (for naked trees) -Xprint:typer (for typechecked trees) -Yshow-trees and its cousins scala.reflect.mirror.showRaw(scala.reflect.mirror.reify(...)) Q: Where do I pull these compiler flags from? A: scala/tools/nsc/settings/ScalaSettings.scala
  • 13. -Yshow-trees // also try -Yshow-trees-stringified // and -Yshow-trees-compact (or both simultaneously) >scalac -Xprint:parser -Yshow-trees HelloWorld.scala [[syntax trees at end of parser]]// Scala source: HelloWorld.scala PackageDef( "<empty>" ModuleDef( 0 "Test" Template( "App" // parents ValDef( private "_" <tpt> <empty> ) ...
  • 14. showRaw scala> scala.reflect.mirror.reify{object Test { println("Hello World!") }} res0: reflect.mirror.Expr[Unit] = ... scala> scala.reflect.mirror.showRaw(res0.tree) res1: String = Block(List(ModuleDef( Modifiers(), newTermName("Test"), Template(List(Ident(newTypeName("Object"))), List( DefDef(Modifiers(), newTermName("<init>"), List(), List(List()), TypeTree(), Block(List(Apply(Select(Super(This(newTypeName("")), newTypeName("")), newTermName("<init>")), List())), Literal(Constant(())))), Apply(Select(Select(This(newTypeName("scala")), newTermName("Predef")), newTermName("println")), List(Literal(Constant("Hello World!")))))))), Literal(Constant(())))
  • 15. Symbols Link definitions and references to definitions. Long-lived, mutable. Declared in scala/reflect/api/Symbols.scala (very much in flux right now!) def foo[T: TypeTag](x: Any) = x.asInstanceOf[T] foo[Long](42) foo, T, x introduce symbols (T actually produces two different symbols). DefDef, TypeDef, ValDef - all of those subtype DefTree. TypeTag, x, T, foo, Long refer to symbols. They are all represented by Idents, which subtype RefTree. Symbols are long-lived. This means that any reference to Int (from a tree or from a type) will point to the same symbol instance.
  • 16. Learn to learn -Xprint:namer or -Xprint:typer -uniqid symbol.kind and -Yshow-symkinds :type -v Don’t create them by yourself. Just don’t, leave it to Namer. In macros most of the time you create naked trees, and Typer will take care of the rest.
  • 17. -uniqid and -Yshow-symkinds >cat Foo.scala def foo[T: TypeTag](x: Any) = x.asInstanceOf[T] foo[Long](42) // there is a mysterious factoid hidden in this printout! >scalac -Xprint:typer -uniqid -Yshow-symkinds Foo.scala [[syntax trees at end of typer]]// Scala source: Foo.scala def foo#8339#METH [T#8340#TPE >: Nothing#4658#CLS <: Any#4657#CLS] (x#9529#VAL: Any#4657#CLS) (implicit evidence$1#9530#VAL: TypeTag#7861#TPE[T#8341#TPE#SKO]) : T#8340#TPE = x#9529#VAL.asInstanceOf#6023#METH[T#8341#TPE#SKO]; Test#14#MODC.this.foo#8339#METH[Long#1641#CLS](42) (scala#29#PK.reflect#2514#PK.‘package‘#3414#PKO .mirror#3463#GET.TypeTag#10351#MOD.Long#10361#GET)
  • 18. :type -v We have just seen how to discover symbols used in trees. However, symbols are also used in types. Thanks to Paul (who hacked this during one of Scala Nights) there’s an easy way to inspect types as well. Corresponding REPL incantation is shown on one of the next slides.
  • 19. Types Immutable, long-lived, sometimes cached case classes declared in scala/reflect/api/Types.scala. Store the information about the full wealth of the Scala type system: members, type arguments, higher kinds, path dependencies, erasures, etc.
  • 20. Learn to learn -Xprint:typer -Xprint-types :type -v -explaintypes
  • 21. -Xprint-types -Xprint-types is yet another option that modifies tree printing. Nothing very fancy, let’s move on to something really cool.
  • 22. :type -v scala> :type -v def impl[T: c.TypeTag](c: Context) = ??? // Type signature [T](c: scala.reflect.makro.Context)(implicit evidence$1: c.TypeTag[T])Nothing // Internal Type structure PolyType( typeParams = List(TypeParam(T)) resultType = MethodType( params = List(TermSymbol(c: ...)) resultType = MethodType( params = List(TermSymbol(implicit evidence$1: ...)) resultType = TypeRef( TypeSymbol(final abstract class Nothing) ) ) ) )
  • 23. -explaintypes >cat Test.scala class Foo { class Bar; def bar(x: Bar) = ??? } object Test extends App { val foo1 = new Foo val foo2 = new Foo foo2.bar(new foo1.Bar) } // prints explanations of type mismatches >scalac -explaintypes Test.scala Test.foo1.Bar <: Test.foo2.Bar? Test.foo1.type <: Test.foo2.type? Test.foo1.type = Test.foo2.type? false false false Test.scala:6: error: type mismatch; ...
  • 24. Big picture Trees are created naked by Parser. Both definitions and references (expressed as ASTs) get their symbols filled in by Namer (tree.symbol). When creating symbols, Namer also creates their completers, lazy thunks that know how to populate symbol types (symbol.info). Typer inspects trees, uses their symbols to transform trees and assign types to them (tree.tpe). Shortly afterwards Pickler kicks in and serializes reachable symbols along with their types into ScalaSignature annotations.
  • 25. Agenda Intro Reflection Universes Demo Macros Summary
  • 26. Universes Universes are environments that pack together trees, symbols and their types. Compiler (scala.tools.nsc.Global) is a universe. Reflective mirror (scala.reflect.mirror) is a universe too. Macro context (scala.reflect.makro.Context) holds a reference to a universe.
  • 27. Symbol tables Universes abstract population of symbol tables. Compiler loads symbols from pickles using its own *.class parser. Reflective mirror uses Java reflection to load and parse ScalaSignatures. Macro context refers to the compiler’s symbol table.
  • 28. Entry points Using a universe depends on your scenario. You can play with compiler’s universe (aka global) in REPL’s :power mode. With mirrors you go through the Mirror interface, e.g. symbolOfInstance or classToType. In a macro context, you import c.mirror. and can use imported factories to create trees and types (don’t create symbols manually, remember?).
  • 29. Path dependency An important quirk is that all universe artifacts are path-dependent on their universe. Note the ”reflect.mirror” prefix in the type of the result printed below. scala> scala.reflect.mirror.reify(2.toString) res0: reflect.mirror.Expr[String] = Expr[String](2.toString()) When you deal with runtime reflection, you simply import scala.reflect.mirror. , and enjoy, because typically there is only one runtime mirror. However with macros it’s more complicated. To pass artifacts around (e.g. into helper functions), you need to also carry the universe with you. Or you can employ the technique outlined in a discussion at scala-internals.
  • 30. Agenda Intro Reflection Universes Demo Macros Summary
  • 31. Inspect members scala> import scala.reflect.mirror import scala.reflect.mirror scala> trait X { def foo: String } defined trait X scala> typeTag[X] res1: TypeTag[X] = ConcreteTypeTag[X] scala> res1.tpe.members res2: Iterable[reflect.mirror.Symbol] = List(method $asInstanceOf, method $isInstanceOf, method sync hronized, method ##, method !=, method ==, method ne, method eq, constructor Object, method notifyAl l, method notify, method clone, method getClass, method hashCode, method toString, method equals, me thod wait, method wait, method wait, method finalize, method asInstanceOf, method isInstanceOf, meth od !=, method ==, method foo)
  • 32. Analyze, typecheck and invoke members val d = new DynamicProxy{ val dynamicProxyTarget = x } d.noargs d.noargs() d.nullary d.value d.- d.$("x") d.overloaded("overloaded with object") d.overloaded(1) val car = new Car d.typeArgs(car) // inferred d.default(1, 3) d.default(1) d.named(1, c=3, b=2) // works, wow The proxy uses reflection that is capable of resolving all these calls. More examples at test/files/run/dynamic-proxy.scala. Implementation is at scala/reflect/DynamicProxy.scala.
  • 33. Defeat erasure scala> def foo[T](x: T) = x.getClass foo: [T](x: T)Class[_ <: T] scala> foo(List(1, 2, 3)) res0: Class[_ <: List[Int]] = class scala.collection.immutable.$colon$colon scala> def foo[T: TypeTag](x: T) = typeTag[T] foo: [T](x: T)(implicit evidence$1: TypeTag[T])TypeTag[T] scala> foo(List(1, 2, 3)) res1: TypeTag[List[Int]] = ConcreteTypeTag[List[Int]] scala> res1.tpe res2: reflect.mirror.Type = List[Int]
  • 34. Compile at runtime import scala.reflect.mirror._ val tree = Apply(Select(Ident("Macros"), newTermName("foo")), List(Literal(Constant(42)))) println(Expr(tree).eval) Eval creates a toolbox under the covers (universe.mkToolBox), which is a full-fledged compiler. Toolbox wraps the input AST, sets its phase to Namer (skipping Parser) and performs the compilation into an in-memory directory. After the compilation is finished, toolbox fires up a classloader that loads and lauches the code.
  • 35. Agenda Intro Reflection Universes Demo Macros Summary
  • 36. Macros In our hackings above, we used the runtime mirror (scala.reflect.mirror) to reflect against program structure. We can do absolutely the same during the compile time. The universe is already there (the compiler itself), the API is there as well (scala.reflect.api.Universe inside the macro context). We only need to ask the compiler to call ourselves during the compilation (currently, our trigger is macro application and the hook is the macro keyword). The end.
  • 37. No, really That’s it.
  • 38. Agenda Intro Reflection Universes Demo Macros Summary
  • 39. Summary In 2.10 you can have all the information about your program that the compiler has (well, almost). This information includes trees, symbols and types. And annotations. And positions. And more. You can reflect at runtime (scala.reflect.mirror) or at compile-time (macros).
  • 40. Status We’re already there. Recently released 2.10.0-M3 includes reflection and macros.
  • 41. Thanks! eugene.burmako@epfl.ch