Date post: | 04-Dec-2014 |
Category: |
Technology |
Upload: | johan-andren |
View: | 1,485 times |
Download: | 1 times |
Macros & reflection
in Scala 2.10
AboutConsultant
JVM/Java - 7 years
Scala - 1 year
me
@apnylle
IMPORTANT WARNING
The reflection/macros in Scala 2.10 are experimental and pretty complex, you might shoot yourself in the foot or worse and be the first one to do it.
(They are also totally awesome)
What
is re
flec
tion?
Photo: Christian Holmér
?
What
is re
flec
tion?
... reflection is the ability of a computer program to examine ... and modify the structure and behavior ... of an object at runtime.
”wikipedia
Hasn’t Scala already got the Java reflection API?!
No support for Scala constructs!
Type erasure
List[Int] + compiler = List :(
B!" ...
w# w$%" &'(#")*%+ b#""#r!
Homoiconic(ness) - express the language in itself
One API for reflection, macros (and the
compiler)
Support for reification
No overhead when not used
Also:
Let’s Look At Some CodeT$,-*%+ *& .)#$/...
What about macros?
A macro (from the Greek μακρό for "big" or "far") in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to a replacement input sequence (also often a sequence of characters) according to a defined procedure.
”wikipedia
Wat!?!
Ok, I Get it
A regular scala function
AST => AST
Called by the compiler
b!" w)$" *& $ ($.r', r#$,,0?
Ok, I Get it&' w)$" *& $% AST, r#$,,0?
if(1 == ”1”) { true } else { false }
if(1.==(”1”)) { true } else { false }
if(1.$eq$eq(”1”)) { true } else { false }
If
if(1.$eq$eq(”1”)) { true } else { false }
Apply
Select
Literal
Constant(1)
Name(”$eq$eq”)Literal
Constant(”1”)
List
Constant(false)
LiteralLiteral
Constant(true)
If
Expr Expr Expr
case class If(cond: Expr, then: Expr, else: Expr)
if(1.$eq$eq(”1”)) { true } else { false }
Transforming an AST to a new AST
w)$" 1' w# 1' w*") *"?
S', W# )$v# $ 2%."*'% r!%%*%+ $" .'(/*,# "*(#
Ideas for macros
Compile time checking of strings
Generic no-runtime-overhead toString
Super efficient loops
zero-overhead logger, assert
'!" 'f ")# "'/ 'f (0 )#$1
Ideas for macros
def myMacro(expr: Expr): Expr {
if (expr != valid dateformat) throw Error
else expr
}
.'(/*,# "*(# .)#.-*%+ 'f &"r*%+&
Ideas for macros
def toStringMacro[T](expr: Expr[T]): Expr[String] {
expr for class name of T +
each field with public getter
}
+#%#r*. "'S"r*%+ w*") z#r'-'v#r)#$1
show some
(Awesome) macros
3(# "'
Finally!(I stopped listening
five slides
ago)
Photo: Paul Lewis
ResourcesOdersky: http://channel9.msdn.com/Events/Lang-
NEXT/Lang-NEXT-2012/Reflection-and-Compilers
Scalamacros.org: http://scalamacros.org/talks/
2012-05-19-ScalaReflect.pdf
Daniel Sobral: http://dcsobral.blogspot.fr/2012/07/
json-serialization-with-reflection-in.html
... w)#r# .$% I ,#$r% ('r#?
S!"#$%: topconf.com / the program page
S&'(!$ (r)*$+,: http://github.com/johanandren/macros-2012
'&"!: [email protected]
,w",,$r: @apnylle
Questions?