KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am working in a Scala embedded DSL and macros are becoming a main tool for achieving my purposes. I am getting an error while trying to reuse a subtree from the incoming macro expression into the resulting one. The situation is quite complex, but (I hope) I have simplified it for its understanding. Suppose we have this code: val y = transform { val x = 3 x } println(y) // prints 3 where 'transform' is the involved macro. Although it could seem it does absolutely nothing, it is really transforming the shown block into this expression: 3 match { case x => x } It is done with this macro implementation: def transform(c: Context)(block: c.Expr[Int]): c.Expr[Int] = { import c.universe._ import definitions._ block.tree match { /* { * val xNam = xVal * xExp * } */ case Block(List(ValDef(_, xNam, _, xVal)), xExp) => println("# " + showRaw(xExp)) // prints Ident(newTermName("x")) c.Expr( Match( xVal, List(CaseDef( Bind(xNam, Ident(newTermName("_"))), EmptyTree, /* xExp */ Ident(newTermName("x")) )))) case _ => c.error(c.enclosingPosition, "Can't transform block to function") block // keep original expression } } Notice that xNam corresponds with the variable name, xVal corresponds with its associated value and finally xExp corresponds with the expression containing the variable. Well, if I print the xExp raw tree I get Ident(newTermName("x")) , and that is exactly what is set in the case RHS. Since the expression could be modified (for instance x+2 instead of x), this is not a valid solution for me. What I want to do is to reuse the xExp tree (see the xExp comment) while altering the 'x' meaning (it is a definition in the input expression but will be a case L
Tags (comma-separated)
Save Edits
Cancel