When in doubt, resetAllAttrs
:
import scala.language.experimental.macros
import scala.reflect.macros.BlackboxContext
def _forRange[A](c: BlackboxContext)(range: c.Expr[Range])(
func: c.Expr[Int => A]
): c.Expr[Unit] = {
import c.universe._
val tree = func.tree match {
case q"($i: $t) => $body" => q"""
val iter = ${range}.iterator
while (iter.hasNext) {
val $i = iter.next
${c.resetAllAttrs(body)} // The only line I've changed.
}
"""
case _ => q""
}
c.Expr(tree)
}
And then:
scala> def forRange[A](range: Range)(func: Int => A) = macro _forRange[A]
defined term macro forRange: [A](range: Range)(func: Int => A)Unit
scala> forRange(0 to 10) { i => println(i) }
0
1
2
3
4
5
6
7
8
9
10
In general, when you're grabbing a tree from one place and plopping it somewhere else, it's likely going to be necessary to use resetAllAttrs
to get all the symbols right.