Skip to content

Instantly share code, notes, and snippets.

@squito
Last active August 12, 2020 20:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squito/7156004 to your computer and use it in GitHub Desktop.
Save squito/7156004 to your computer and use it in GitHub Desktop.
some basic macros with quasiquotes. Accompanies this blog post <http://imranrashid.com/posts/learning-scala-macros/>. Partially a translation of this example <http://www.warski.org/blog/2012/12/starting-with-scala-macros-a-short-tutorial/> to quasiquotes.
def getValMacro(c: Context)(s: c.Expr[Any]) : c.Expr[Any] = {
import c.universe._
val q"val $name = $value" = s.tree
c.Expr(value)
}
def getVal(s: Any) = macro getValMacro
getVal{val x = 17}
error: exception during macro expansion:
scala.MatchError: {
val x: Int = 17;
()
} (of class scala.reflect.internal.Trees$Block)
at .getValMacro(<console>:13)
import language.experimental.macros
import reflect.macros.Context
import scala.annotation.StaticAnnotation
import scala.reflect.runtime.{universe => ru}
def debugMacro(c: Context)(s: c.Expr[Any]) : c.Expr[Any] = {
import c.universe._
val paramRep = show(s.tree)
c.Expr(q"""println($paramRep + " = " + $s)""")
}
def debug(s: Any) = macro debugMacro
def getValMacro(c: Context)(s: c.Expr[Any]) : c.Expr[Any] = {
import c.universe._
val q"val $name = $value" = s.tree match {case Block(List(valdef),_) => valdef}
c.Expr(value)
}
def getVal(s: Any) = macro getValMacro
scala> getVal{val x = 17}
res5: Int = 17
def printTreeMacro(c: Context)(s: c.Expr[Any]) : c.Expr[Any] = {
println(showRaw(s.tree))
c.universe.reify{()}
}
def printTree(s:Any) = macro printTreeMacro
scala> printTree{val x = 17}
Block(List(ValDef(Modifiers(0, , List()), x, TypeTree(), Literal(Constant(17)))), Literal(Constant(())))
scala> showRaw(q"val x = 17")
res0: String = ValDef(Modifiers(), newTermName("x"), TypeTree(), Literal(Constant(17)))
scala> val x = 17
x: Int = 17
scala> debug(x)
$line23.$read.$iw.$iw.$iw.x = 17
scala> def debugMacro(c: Context)(s: c.Expr[Any]) : c.Expr[Any] = {
| import c.universe._
| val paramRep = show(s.tree)
| q"""println($paramRep + " = " + $s)"""
| }
<console>:19: error: type mismatch;
found : c.universe.Apply
required: c.Expr[Any]
(which expands to) c.universe.Expr[Any]
q"""println($paramRep + " = " + $s)"""
^
@emariacher
Copy link

@changetip, send 4 mariacher to @squito

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment