Created
January 2, 2012 01:39
-
-
Save xeno-by/1548942 to your computer and use it in GitHub Desktop.
First prototype of Scala quasiquotes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** This demo shows: | |
* Syntax for quasiquotations | |
* String interpolation as a quasiquote | |
* Code quoting as a quasiquote | |
* Pattern matching against code quotes | |
* Some capabilities of brand new Scala reflection API (typechecking, compiling and running ASTs) | |
*/ | |
>scala -Xquasiquotes -Yquasiquote-debug | |
Welcome to Scala version 2.10.0.dev-1473-ga6c67da (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_25). | |
Type in expressions to have them evaluated. | |
Type :help for more information. | |
scala> val world = "world" | |
world: String = world | |
scala> println("hello, $world!") | |
hello, $world! | |
scala> println(s"hello, $world!") | |
quasiquote literal: new scala.reflect.QuasiquoteLiteral(List("hello, ", "!"), List(world), List("")).s() | |
string interpolation: new scala.runtime.StringContext("hello, ", "!").show(world) | |
hello, world! | |
scala> val x = 2 | |
x: Int = 2 | |
scala> val x = c"2" | |
quasiquote literal: new scala.reflect.QuasiquoteLiteral(List("2"), List(), List()).c() | |
code quotation: scala.reflect.Code.lift(2) | |
x: scala.reflect.Code[Int] = Code(tree = 2, manifest = Int) | |
scala> val y = c"2" | |
quasiquote literal: new scala.reflect.QuasiquoteLiteral(List("2"), List(), List()).c() | |
code quotation: scala.reflect.Code.lift(2) | |
y: scala.reflect.Code[Int] = Code(tree = 2, manifest = Int) | |
scala> val four = c"$x + $y".tree | |
quasiquote literal: new scala.reflect.QuasiquoteLiteral(List("", " + ", ""), List(x, y), List("", "")).c() | |
code quotation: scala.reflect.Code.lift(scala.reflect.Code.splice($line5.$read.$iw.$iw.x). | |
$plus(scala.reflect.Code.splice($line6.$read.$iw.$iw.y))) | |
four: reflect.mirror.Tree = 2.$plus(2) | |
scala> four match { | |
| case c"$two + 2" => println(showRaw(two)) | |
| case _ => println("fail") | |
| } | |
quasiquote pattern: new scala.reflect.QuasiquotePattern(List("", " + 2"), List(two), List("")).c() | |
code pattern: case scala.reflect.mirror.Apply(scala.reflect.mirror.Select((two @ _), ($name$$plus @ _)), | |
List(scala.reflect.mirror.Literal(scala.reflect.mirror.Constant(2)))) | |
if true.$amp$amp($name$$plus.toString.$eq$eq("$plus")) => println(showRaw(two)) | |
Literal(Constant(2)) | |
scala> toolbox.typeCheck(four) | |
res6: reflect.mirror.Tree = 4 | |
scala> res6.tpe | |
res7: reflect.mirror.Type = Int(4) | |
scala> toolbox.runExpr(four) | |
res8: Any = 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment