SlideShare uma empresa Scribd logo
1 de 36
Baixar para ler offline
The State of the Meta 
Eugene Burmako (@xeno by) 
Ecole Polytechnique Federale de Lausanne 
http://scalameta.org/ 
22 November 2014
Outline 
▶ Why metaprogramming matters 
▶ The present (scala.re
ect) 
▶ The future (scala.meta) 
2
Why metaprogramming matters 
3
Metaprogramming is... 
Metaprogramming is the writing of computer programs that 
write or manipulate other programs or themselves as their data. 
|Wikipedia 
4
Use case #1: Code generation 
Sometimes you have to reach for a sledgehammer: 
▶ High performance 
▶ Integration with external systems 
▶ Abstraction over heterogeneous datatypes 
5
Use case #2: Advanced static checks 
Types are useful, but every now and then they fall short: 
▶ Restrict the types of variables that are captured in closures 
▶ Ensure that communication between actors is sound 
▶ Prevent over
ows or under
ows in computation-heavy code 
6
Use case #3: Advanced domain-speci
c languages 
Even 
exible syntax and powerful types have their limits: 
▶ LINQ 
▶ async/await 
▶ External DSLs 
7
Use case #4: Tooling 
▶ Style checking 
▶ Refactoring 
▶ Incremental compilation 
▶ And much-much more 
8
The present (scala.re
ect) 
9
The present (scala.re
ect) 
▶ Decent support for compile-time metaprogramming (macros) 
▶ Some support for runtime metaprogramming (re
ection, codegen) 
▶ Hardcore compiler internals or reinvented wheels for everything else 
10
Macros by example 
def createArray[T: ClassTag](size: Int, el: T) = { 
val a = new Array[T](size) 
for (i - 0 until size) a(i) = el 
a 
} 
▶ We want to write beautiful generic code, and Scala makes that easy 
▶ Unfortunately, abstractions oftentimes bring overhead 
11
Macros by example 
Object createArray(int size, Object el, ClassTag tag) { 
Object a = tag.newArray(size); 
for (int i=0; isize; i++) ScalaRunTime.array_update(...); 
return a; 
} 
▶ Scala runs on the JVM, so polymorphic signatures have to be erased 
▶ Erasure leads to boxing and boxing creates signi
cant slowdowns 
▶ The snippet above shows a sketch of what createArray compiles to 
12
Macros by example 
def createArray[@specialized T: ClassTag](...) = { 
val a = new Array[T](size) 
for (i - 0 until size) a(i) = el 
a 
} 
▶ Methods can be specialized, but it's viral and heavyweight 
▶ Viral = the entire call chain needs to be specialized 
▶ Heavyweight = specialization leads to duplication of bytecode 
13
Macros by example 
def createArray[T: ClassTag](size: Int, el: T) = { 
val a = new Array[T](size) 
def specBody[@specialized T](a: Array[T], el: T) = { 
for (i - 0 until size) a(i) = el 
} 
classTag[T] match { 
case ClassTag.Int = specBody( 
a.asInstanceOf[Array[Int]], el.asInstanceOf[Int]) 
... 
} 
a 
} 
▶ We want to specialize just as much as we need 
▶ But that's tiresome to do by hand, and this is where macros shine 
14
Macros by example 
def specialized[T](x: = T) = macro impl[T] 
def createArray[T: ClassTag](size: Int, el: T) = { 
val a = new Array[T](size) 
specialized[T] { 
for (i - 0 until size) a(i) = el 
} 
a 
} 
▶ specialized macro gets pretty code and transforms it into fast code 
▶ The transformation is carried out by an associated metaprogram impl 
▶ For more details, see Bridging Islands of Specialized Code 
15
How macros work 
▶ We publish the language model as part of the standard distribution 
▶ scala-reflect.jar contains de
nitions of trees, symbols, types, etc 
▶ Macros are written against data structures from scala.re
ect 
▶ And executed inside scalac which implements the scala.re
ect API 
16
How macros work 
def specialized[T](x: = T) = macro impl[T] 
def impl[T](c: scala.reflect.macros.Context) 
(x: c.Tree)(implicit T: c.WeakTypeTag[T]) = { 
import c.universe._ 
val (specVars, specBody) = Helpers.specialize(x, T) 
q 
def specBody[@specialized T](..$specVars) = $specBody 
classTag[$T] match { case ..$cases } 
 
} 
▶ The entry point to compile-time metaprogramming is a context 
▶ From there we can import a universe of trees, symbols, types, etc 
17
How macros work 
def specialized[T](x: = T) = macro impl[T] 
def impl[T](c: scala.reflect.macros.Context) 
(x: c.Tree)(implicit T: c.WeakTypeTag[T]) = { 
import c.universe._ 
val (specVars, specBody) = Helpers.specialize(x, T) 
q 
def specBody[@specialized T](..$specVars) = $specBody 
classTag[$T] match { case ..$cases } 
 
} 
▶ Re
ection artifacts that model Scala code are
rst-class 
▶ We can pass them around to/from helpers, can create new ones 
18
How macros work 
def specialized[T](x: = T) = macro impl[T] 
def impl[T](c: scala.reflect.macros.Context) 
(x: c.Tree)(implicit T: c.WeakTypeTag[T]) = { 
import c.universe._ 
val (specVars, specBody) = Helpers.specialize(x, T) 
q 
def specBody[@specialized T](..$specVars) = $specBody 
classTag[$T] match { case ..$cases } 
 
} 
▶ Upon completion, a macro returns a tree representing new code 
▶ This tree will replace the macro invocation at the call site 
19
There's more 
▶ Type providers 
▶ Automatic generation of typeclass instances 
▶ Language virtualization 
▶ Deep integration with external DSLs 
▶ For details see our What Are Macros Good For? talk 
20
The future (scala.meta) 
21
The future (scala.meta) 
▶ This year we set out on a journey to create an ultimate 
metaprogramming API 
▶ Here we'll tell you about our design decisions and their impact 
22
scala.meta principles 
▶ Language model should be independent of language implementations 
▶ Interface for syntax trees should be based on hygienic quasiquotes 
▶ Binaries should provide access to their attributed abstract syntax trees 
23
Principle #1: Independent language model 
▶ scala.reflect grew organically from scalac internals 
▶ That was a nice shortcut to get things going easily 
▶ But in the long run dependence on scalac makes everything harder 
24
Principle #1: Independent language model 
25
Principle #1: Independent language model 
Diversity is real: 
▶ ...Intellij (a reimplementation of Scala's typechecker) 
▶ ...Dotty (the next generation Scala compiler) 
▶ ...Typelevel (an experimental community fork) 
▶ ...Policy (a compiler/language technology fork) 
26
Principle #2: Hygienic quasiquotes 
ClassDef( 
NoMods, 
newTypeName(D), 
Nil, 
Template( 
List(Ident(newTypeName(C))), 
emptyValDef, 
List(DefDef(NoMods, nme.CONSTRUCTOR, ...)))) 
▶ Once, the most reliable way to do ASTs was via vanilla datatypes 
▶ Above you can see what it took to say class D extends C 
▶ Needless to say, only brave souls cared to use such an API 
27
Principle #2: Hygienic quasiquotes 
val tree = qclass D extends C 
val qclass $_ extends ..$parents = tree 
▶ Then we introduced quasiquotes, a template-based approach to ASTs 
▶ Quasiquotes can create and match ASTs with minimal overhead 
▶ At this point our metaprogramming API started to look friendly 
28
Principle #2: Hygienic quasiquotes 
import foo.bar.C 
val tree = qclass D extends C 
qclass C; $tree 
▶ The
nal puzzle to solve is prevention of name clashes 
▶ This is what is called hygiene of a metaprogramming API 
▶ Probably the most common pitfall in Scala macros at the moment 
29
Principle #3: Persistent syntax trees 
▶ Every compilation produces attributed syntax trees 
▶ These trees contain a wealth of semantic information about programs 
▶ These trees get thrown away every time 
30
Principle #3: Persistent syntax trees 
What if we saved attributed trees instead of throwing them away? 
▶ Easy interpretation 
▶ Easy code analysis 
▶ And other neat metaprogramming tricks 
31

Mais conteúdo relacionado

Mais procurados

11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)smumbahelp
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWithTheBest
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#foreverredpb
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
New Features in Dotnet Niku Software
New Features in Dotnet Niku SoftwareNew Features in Dotnet Niku Software
New Features in Dotnet Niku SoftwareJaganathRao
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesSyed Zaid Irshad
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstractionHoang Nguyen
 

Mais procurados (20)

11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
Op ps
Op psOp ps
Op ps
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Structure in c sharp
Structure in c sharpStructure in c sharp
Structure in c sharp
 
Four Pillers Of OOPS
Four Pillers Of OOPSFour Pillers Of OOPS
Four Pillers Of OOPS
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Java
JavaJava
Java
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
iOS Basic
iOS BasiciOS Basic
iOS Basic
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
New Features in Dotnet Niku Software
New Features in Dotnet Niku SoftwareNew Features in Dotnet Niku Software
New Features in Dotnet Niku Software
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
class and objects
class and objectsclass and objects
class and objects
 
Multiple file programs, inheritance, templates
Multiple file programs, inheritance, templatesMultiple file programs, inheritance, templates
Multiple file programs, inheritance, templates
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 

Destaque

F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014Phillip Trelford
 
Максим Харченко. Erlang lincx
Максим Харченко. Erlang lincxМаксим Харченко. Erlang lincx
Максим Харченко. Erlang lincxAlina Dolgikh
 
Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Alina Dolgikh
 
Максим Лапшин. Erlang production
Максим Лапшин. Erlang productionМаксим Лапшин. Erlang production
Максим Лапшин. Erlang productionAlina Dolgikh
 
Tame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLsTame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLsYan Cui
 

Destaque (6)

F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014F# Eye For The C# Guy - f(by) Minsk 2014
F# Eye For The C# Guy - f(by) Minsk 2014
 
Максим Харченко. Erlang lincx
Максим Харченко. Erlang lincxМаксим Харченко. Erlang lincx
Максим Харченко. Erlang lincx
 
Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.
 
Максим Лапшин. Erlang production
Максим Лапшин. Erlang productionМаксим Лапшин. Erlang production
Максим Лапшин. Erlang production
 
Heather Miller
Heather MillerHeather Miller
Heather Miller
 
Tame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLsTame cloud complexity with F#-powered DSLs
Tame cloud complexity with F#-powered DSLs
 

Semelhante a The State of Scala Metaprogramming and the Future of scala.meta

ScilabTEC 2015 - Silkan
ScilabTEC 2015 - SilkanScilabTEC 2015 - Silkan
ScilabTEC 2015 - SilkanScilab
 
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...Alessandro Confetti
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019Paulo Clavijo
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++Nimrita Koul
 
The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2Y Watanabe
 
Dot Net Fundamentals
Dot Net FundamentalsDot Net Fundamentals
Dot Net FundamentalsLiquidHub
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfjorgeulises3
 
Cryptography and secure systems
Cryptography and secure systemsCryptography and secure systems
Cryptography and secure systemsVsevolod Stakhov
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the DomainVictor Rentea
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and VerificationKapilRaghunandanTrip
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programmingsmumbahelp
 

Semelhante a The State of Scala Metaprogramming and the Future of scala.meta (20)

ScilabTEC 2015 - Silkan
ScilabTEC 2015 - SilkanScilabTEC 2015 - Silkan
ScilabTEC 2015 - Silkan
 
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
XConf 2022 - Code As Data: How data insights on legacy codebases can fill the...
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
 
The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2
 
Dot Net Fundamentals
Dot Net FundamentalsDot Net Fundamentals
Dot Net Fundamentals
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
 
Cryptography and secure systems
Cryptography and secure systemsCryptography and secure systems
Cryptography and secure systems
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
C#ppt
C#pptC#ppt
C#ppt
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Ej Chpt#4 Final
Ej Chpt#4 FinalEj Chpt#4 Final
Ej Chpt#4 Final
 
C Programming - Refresher - Part IV
C Programming - Refresher - Part IVC Programming - Refresher - Part IV
C Programming - Refresher - Part IV
 
Clean architecture - Protecting the Domain
Clean architecture - Protecting the DomainClean architecture - Protecting the Domain
Clean architecture - Protecting the Domain
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and Verification
 
Bca5020 visual programming
Bca5020  visual programmingBca5020  visual programming
Bca5020 visual programming
 

Mais de Volha Banadyseva

Андрей Светлов. Aiohttp
Андрей Светлов. AiohttpАндрей Светлов. Aiohttp
Андрей Светлов. AiohttpVolha Banadyseva
 
Сергей Зефиров
Сергей ЗефировСергей Зефиров
Сергей ЗефировVolha Banadyseva
 
Валерий Прытков, декан факультета КСиС, БГУИР
Валерий Прытков, декан факультета КСиС, БГУИРВалерий Прытков, декан факультета КСиС, БГУИР
Валерий Прытков, декан факультета КСиС, БГУИРVolha Banadyseva
 
Елена Локтева, «Инфопарк»
Елена Локтева, «Инфопарк»Елена Локтева, «Инфопарк»
Елена Локтева, «Инфопарк»Volha Banadyseva
 
Татьяна Милова, директор института непрерывного образования БГУ
Татьяна Милова, директор института непрерывного образования БГУТатьяна Милова, директор института непрерывного образования БГУ
Татьяна Милова, директор института непрерывного образования БГУVolha Banadyseva
 
Trillhaas Goetz. Innovations in Google and Global Digital Trends
Trillhaas Goetz. Innovations in Google and Global Digital TrendsTrillhaas Goetz. Innovations in Google and Global Digital Trends
Trillhaas Goetz. Innovations in Google and Global Digital TrendsVolha Banadyseva
 
Александр Чекан. 28 правДИвых слайдов о белорусах в интернете
Александр Чекан. 28 правДИвых слайдов о белорусах в интернетеАлександр Чекан. 28 правДИвых слайдов о белорусах в интернете
Александр Чекан. 28 правДИвых слайдов о белорусах в интернетеVolha Banadyseva
 
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в storeМастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в storeVolha Banadyseva
 
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App StoreБахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App StoreVolha Banadyseva
 
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...Volha Banadyseva
 
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google PlayЕвгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google PlayVolha Banadyseva
 
Евгений Козяк. Tips & Tricks мобильного прототипирования
Евгений Козяк. Tips & Tricks мобильного прототипированияЕвгений Козяк. Tips & Tricks мобильного прототипирования
Евгений Козяк. Tips & Tricks мобильного прототипированияVolha Banadyseva
 
Егор Белый. Модели успешной монетизации мобильных приложений
Егор Белый. Модели успешной монетизации мобильных приложенийЕгор Белый. Модели успешной монетизации мобильных приложений
Егор Белый. Модели успешной монетизации мобильных приложенийVolha Banadyseva
 
Станислав Пацкевич. Инструменты аналитики для мобильных платформ
Станислав Пацкевич. Инструменты аналитики для мобильных платформСтанислав Пацкевич. Инструменты аналитики для мобильных платформ
Станислав Пацкевич. Инструменты аналитики для мобильных платформVolha Banadyseva
 
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...Volha Banadyseva
 
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...Volha Banadyseva
 
Юлия Ерина. Augmented Reality Games: становление и развитие
Юлия Ерина. Augmented Reality Games: становление и развитиеЮлия Ерина. Augmented Reality Games: становление и развитие
Юлия Ерина. Augmented Reality Games: становление и развитиеVolha Banadyseva
 
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позжеАлександр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позжеVolha Banadyseva
 
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...Volha Banadyseva
 
Кирилла Кравченко. Гейминдустрия: эволюция
Кирилла Кравченко. Гейминдустрия: эволюцияКирилла Кравченко. Гейминдустрия: эволюция
Кирилла Кравченко. Гейминдустрия: эволюцияVolha Banadyseva
 

Mais de Volha Banadyseva (20)

Андрей Светлов. Aiohttp
Андрей Светлов. AiohttpАндрей Светлов. Aiohttp
Андрей Светлов. Aiohttp
 
Сергей Зефиров
Сергей ЗефировСергей Зефиров
Сергей Зефиров
 
Валерий Прытков, декан факультета КСиС, БГУИР
Валерий Прытков, декан факультета КСиС, БГУИРВалерий Прытков, декан факультета КСиС, БГУИР
Валерий Прытков, декан факультета КСиС, БГУИР
 
Елена Локтева, «Инфопарк»
Елена Локтева, «Инфопарк»Елена Локтева, «Инфопарк»
Елена Локтева, «Инфопарк»
 
Татьяна Милова, директор института непрерывного образования БГУ
Татьяна Милова, директор института непрерывного образования БГУТатьяна Милова, директор института непрерывного образования БГУ
Татьяна Милова, директор института непрерывного образования БГУ
 
Trillhaas Goetz. Innovations in Google and Global Digital Trends
Trillhaas Goetz. Innovations in Google and Global Digital TrendsTrillhaas Goetz. Innovations in Google and Global Digital Trends
Trillhaas Goetz. Innovations in Google and Global Digital Trends
 
Александр Чекан. 28 правДИвых слайдов о белорусах в интернете
Александр Чекан. 28 правДИвых слайдов о белорусах в интернетеАлександр Чекан. 28 правДИвых слайдов о белорусах в интернете
Александр Чекан. 28 правДИвых слайдов о белорусах в интернете
 
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в storeМастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
Мастер-класс Ильи Красинского и Елены Столбовой. Жизнь до и после выхода в store
 
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App StoreБахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
Бахрам Исмаилов. Продвижение мобильного приложение - оптимизация в App Store
 
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
Евгений Пальчевский. Что можно узнать из отзывов пользователей в мобильных ма...
 
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google PlayЕвгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
Евгений Невгень. Оптимизация мета-данных приложения для App Store и Google Play
 
Евгений Козяк. Tips & Tricks мобильного прототипирования
Евгений Козяк. Tips & Tricks мобильного прототипированияЕвгений Козяк. Tips & Tricks мобильного прототипирования
Евгений Козяк. Tips & Tricks мобильного прототипирования
 
Егор Белый. Модели успешной монетизации мобильных приложений
Егор Белый. Модели успешной монетизации мобильных приложенийЕгор Белый. Модели успешной монетизации мобильных приложений
Егор Белый. Модели успешной монетизации мобильных приложений
 
Станислав Пацкевич. Инструменты аналитики для мобильных платформ
Станислав Пацкевич. Инструменты аналитики для мобильных платформСтанислав Пацкевич. Инструменты аналитики для мобильных платформ
Станислав Пацкевич. Инструменты аналитики для мобильных платформ
 
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
Артём Азевич. Эффективные подходы к разработке приложений. Как найти своего п...
 
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
Дина Сударева. Развитие игровой команды и ее самоорганизация. Роль менеджера ...
 
Юлия Ерина. Augmented Reality Games: становление и развитие
Юлия Ерина. Augmented Reality Games: становление и развитиеЮлия Ерина. Augmented Reality Games: становление и развитие
Юлия Ерина. Augmented Reality Games: становление и развитие
 
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позжеАлександр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
Александр Дзюба. Знать игрока: плейтест на стадии прототипа и позже
 
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
Светлана Половинкина. О чём говорит игрок: опросы как инструмент принятия биз...
 
Кирилла Кравченко. Гейминдустрия: эволюция
Кирилла Кравченко. Гейминдустрия: эволюцияКирилла Кравченко. Гейминдустрия: эволюция
Кирилла Кравченко. Гейминдустрия: эволюция
 

Último

Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 

Último (20)

Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 

The State of Scala Metaprogramming and the Future of scala.meta

  • 1. The State of the Meta Eugene Burmako (@xeno by) Ecole Polytechnique Federale de Lausanne http://scalameta.org/ 22 November 2014
  • 2. Outline ▶ Why metaprogramming matters ▶ The present (scala.re ect) ▶ The future (scala.meta) 2
  • 4. Metaprogramming is... Metaprogramming is the writing of computer programs that write or manipulate other programs or themselves as their data. |Wikipedia 4
  • 5. Use case #1: Code generation Sometimes you have to reach for a sledgehammer: ▶ High performance ▶ Integration with external systems ▶ Abstraction over heterogeneous datatypes 5
  • 6. Use case #2: Advanced static checks Types are useful, but every now and then they fall short: ▶ Restrict the types of variables that are captured in closures ▶ Ensure that communication between actors is sound ▶ Prevent over ows or under ows in computation-heavy code 6
  • 7. Use case #3: Advanced domain-speci
  • 8. c languages Even exible syntax and powerful types have their limits: ▶ LINQ ▶ async/await ▶ External DSLs 7
  • 9. Use case #4: Tooling ▶ Style checking ▶ Refactoring ▶ Incremental compilation ▶ And much-much more 8
  • 11. The present (scala.re ect) ▶ Decent support for compile-time metaprogramming (macros) ▶ Some support for runtime metaprogramming (re ection, codegen) ▶ Hardcore compiler internals or reinvented wheels for everything else 10
  • 12. Macros by example def createArray[T: ClassTag](size: Int, el: T) = { val a = new Array[T](size) for (i - 0 until size) a(i) = el a } ▶ We want to write beautiful generic code, and Scala makes that easy ▶ Unfortunately, abstractions oftentimes bring overhead 11
  • 13. Macros by example Object createArray(int size, Object el, ClassTag tag) { Object a = tag.newArray(size); for (int i=0; isize; i++) ScalaRunTime.array_update(...); return a; } ▶ Scala runs on the JVM, so polymorphic signatures have to be erased ▶ Erasure leads to boxing and boxing creates signi
  • 14. cant slowdowns ▶ The snippet above shows a sketch of what createArray compiles to 12
  • 15. Macros by example def createArray[@specialized T: ClassTag](...) = { val a = new Array[T](size) for (i - 0 until size) a(i) = el a } ▶ Methods can be specialized, but it's viral and heavyweight ▶ Viral = the entire call chain needs to be specialized ▶ Heavyweight = specialization leads to duplication of bytecode 13
  • 16. Macros by example def createArray[T: ClassTag](size: Int, el: T) = { val a = new Array[T](size) def specBody[@specialized T](a: Array[T], el: T) = { for (i - 0 until size) a(i) = el } classTag[T] match { case ClassTag.Int = specBody( a.asInstanceOf[Array[Int]], el.asInstanceOf[Int]) ... } a } ▶ We want to specialize just as much as we need ▶ But that's tiresome to do by hand, and this is where macros shine 14
  • 17. Macros by example def specialized[T](x: = T) = macro impl[T] def createArray[T: ClassTag](size: Int, el: T) = { val a = new Array[T](size) specialized[T] { for (i - 0 until size) a(i) = el } a } ▶ specialized macro gets pretty code and transforms it into fast code ▶ The transformation is carried out by an associated metaprogram impl ▶ For more details, see Bridging Islands of Specialized Code 15
  • 18. How macros work ▶ We publish the language model as part of the standard distribution ▶ scala-reflect.jar contains de
  • 19. nitions of trees, symbols, types, etc ▶ Macros are written against data structures from scala.re ect ▶ And executed inside scalac which implements the scala.re ect API 16
  • 20. How macros work def specialized[T](x: = T) = macro impl[T] def impl[T](c: scala.reflect.macros.Context) (x: c.Tree)(implicit T: c.WeakTypeTag[T]) = { import c.universe._ val (specVars, specBody) = Helpers.specialize(x, T) q def specBody[@specialized T](..$specVars) = $specBody classTag[$T] match { case ..$cases } } ▶ The entry point to compile-time metaprogramming is a context ▶ From there we can import a universe of trees, symbols, types, etc 17
  • 21. How macros work def specialized[T](x: = T) = macro impl[T] def impl[T](c: scala.reflect.macros.Context) (x: c.Tree)(implicit T: c.WeakTypeTag[T]) = { import c.universe._ val (specVars, specBody) = Helpers.specialize(x, T) q def specBody[@specialized T](..$specVars) = $specBody classTag[$T] match { case ..$cases } } ▶ Re ection artifacts that model Scala code are
  • 22. rst-class ▶ We can pass them around to/from helpers, can create new ones 18
  • 23. How macros work def specialized[T](x: = T) = macro impl[T] def impl[T](c: scala.reflect.macros.Context) (x: c.Tree)(implicit T: c.WeakTypeTag[T]) = { import c.universe._ val (specVars, specBody) = Helpers.specialize(x, T) q def specBody[@specialized T](..$specVars) = $specBody classTag[$T] match { case ..$cases } } ▶ Upon completion, a macro returns a tree representing new code ▶ This tree will replace the macro invocation at the call site 19
  • 24. There's more ▶ Type providers ▶ Automatic generation of typeclass instances ▶ Language virtualization ▶ Deep integration with external DSLs ▶ For details see our What Are Macros Good For? talk 20
  • 26. The future (scala.meta) ▶ This year we set out on a journey to create an ultimate metaprogramming API ▶ Here we'll tell you about our design decisions and their impact 22
  • 27. scala.meta principles ▶ Language model should be independent of language implementations ▶ Interface for syntax trees should be based on hygienic quasiquotes ▶ Binaries should provide access to their attributed abstract syntax trees 23
  • 28. Principle #1: Independent language model ▶ scala.reflect grew organically from scalac internals ▶ That was a nice shortcut to get things going easily ▶ But in the long run dependence on scalac makes everything harder 24
  • 29. Principle #1: Independent language model 25
  • 30. Principle #1: Independent language model Diversity is real: ▶ ...Intellij (a reimplementation of Scala's typechecker) ▶ ...Dotty (the next generation Scala compiler) ▶ ...Typelevel (an experimental community fork) ▶ ...Policy (a compiler/language technology fork) 26
  • 31. Principle #2: Hygienic quasiquotes ClassDef( NoMods, newTypeName(D), Nil, Template( List(Ident(newTypeName(C))), emptyValDef, List(DefDef(NoMods, nme.CONSTRUCTOR, ...)))) ▶ Once, the most reliable way to do ASTs was via vanilla datatypes ▶ Above you can see what it took to say class D extends C ▶ Needless to say, only brave souls cared to use such an API 27
  • 32. Principle #2: Hygienic quasiquotes val tree = qclass D extends C val qclass $_ extends ..$parents = tree ▶ Then we introduced quasiquotes, a template-based approach to ASTs ▶ Quasiquotes can create and match ASTs with minimal overhead ▶ At this point our metaprogramming API started to look friendly 28
  • 33. Principle #2: Hygienic quasiquotes import foo.bar.C val tree = qclass D extends C qclass C; $tree ▶ The
  • 34. nal puzzle to solve is prevention of name clashes ▶ This is what is called hygiene of a metaprogramming API ▶ Probably the most common pitfall in Scala macros at the moment 29
  • 35. Principle #3: Persistent syntax trees ▶ Every compilation produces attributed syntax trees ▶ These trees contain a wealth of semantic information about programs ▶ These trees get thrown away every time 30
  • 36. Principle #3: Persistent syntax trees What if we saved attributed trees instead of throwing them away? ▶ Easy interpretation ▶ Easy code analysis ▶ And other neat metaprogramming tricks 31
  • 37. Principle #3: Persistent syntax trees 32
  • 38. Principle #3: Persistent syntax trees It turns out that tree persistence is so much more: ▶ Separate the frontend and the backend of the compiler ▶ Typed syntax trees become the new bytecode ▶ Linker produces binaries native to target platforms ▶ Solves bincompat problems and enables amazing optimizations! 33
  • 39. Our status ▶ We have an initial design of the metaprogramming API ▶ And are currently validating it on a number of use cases ▶ Something publicly usable should appear next year ▶ Most likely as a compiler plugin for Scala 2.11 34
  • 41. Summary ▶ Metaprogramming is useful, and Scala programmers use it ▶ You don't just grow a metaprogramming API from compiler internals ▶ High tech is paramount for usability (quasiquotes, hygiene, etc) ▶ Tree persistence can enable unexpected technological advances 36