How to inspect implementation with Scala macros -
i'd need find out if method used in method implementation. example, have glorious app:
object test extends app { def getgreetings = array.fill(2)("hello") println(getgreetings.mkstring("\n")) }
i'd test if method getgreetings
uses function fill
of array's companion object. test succeed above implementation , fail example with:
def getgreetings = array("hello", "hello") // nah, fill isn't used
with of this video learned can inspect implementation macros this:
def printtree(title: string)(expr: any): unit = macro printtreemacro def printtreemacro(c: context)(title: c.tree)(expr: c.tree) = { import c.universe._ val code : string = showcode(expr) val raw : string = showraw(expr) q""" println( $title.touppercase + "\n\n" + $code + "\n\n" + $raw + "\n\n" ) """ } printtree("method") { val = array.fill(2)("hello") }
now printtree
reveals fill
method used:
block(list(valdef(modifiers(), termname("a"), typetree(), apply(apply(apply(typeapply(select(select(ident(scala), scala.array), termname("fill")), list(typetree())), list(literal(constant(2)))), list(literal(constant("hello")))), list(typed(apply(typeapply(select(ident(scala.reflect.classtag), termname("apply")), list(typetree())), list(literal(constant(string)))), typetree()))))), literal(constant(())))
the missing piece here how same code of method, tree what's inside method getgreetings
.
thanks in advance :)
Comments
Post a Comment