macros - scala - insert value into quasiquote -
unfortunately, intuitive way,
val world = "earth" val tree = q"""println("hello $world")"""
results in
error:(16, 36) don't know how unquote here val tree = q"""println("hello $world")""" ^
because $
within quasiquotes expects tree
.
val world = "earth" val tree = q"""println(${c.literal(s"hello $world")})"""
works, ugly , intellij warning c.literal
deprecated , should use quasiquotes, instead.
so ... how do this?
update
in response flavian's comment:
import scala.language.experimental.macros import scala.reflect.macros._ object testmacros { def dotest() = macro impl def impl(c: blackbox.context)(): c.expr[unit] = { import c.universe._ //access ast classes /* val world = "earth" val tree = q"""println(${c.literal(s"hello $world")})""" */ val world = termname("earth") val tree = q"""println("hello $world")""" tree match { case q"""println("hello earth")""" => println("succeeded") case _ => c.abort(c.enclosingposition, s"huh? was: $tree") } c.expr(tree) //wrap tree , tag type } }
gives
error:(18, 40) don't know how unquote here val tree = q"""println("hello $world")""" ^
you need termname
or that's compiler primitive.
the real problem mixing interpolators, without realising. interpolator in hello world string interpolator, not quasiquote 1 @ unquoting trees suggest.
this 1 way go it:
import c.universe._ val world = termname("earth") val tree = q"""println("hello" + ${world.decodedname.tostring})"""
Comments
Post a Comment