简体   繁体   中英

Is it possible to capture some value for use inside of `splice` part of `reify` macro?

For example, I have some list and want to iterate on it, and do macro transformation on each value:

reify {
  someIntListExpr.splice.foreach { i =>
    // transform is a macro of the form 'transform(c: Context)(i: c.Expr[Int]): c.Expr[Unit]
    transform(i).splice
  }
}

But the compiler spits out error message:

found: Int
required: c.universe.Expr[Int]

Is there a way to fix it?

In simple cases this will do the trick:

someIntListExpr.splice.foreach { i =>
  transformImpl(c)(c.Expr[Int](Ident(newTermName("i")))).splice
}

Alternatively you can create method like this

def trans(i: Int): Unit = macro transform

and apply it:

reify {
  someIntListExpr.splice.foreach { i =>
    trans(i)
  }
}

Sometimes you can actually get List[c.Expr[Unit]] .

If your method ( def myMethod(l: List[Int]): unti = macro myMethodImpl ) is called like myMethod(List(1, 2, x)) then you can get List[c.Expr[Unit]] :

def myMethodImpl(c: Context)(l: c.Expr[List[Int]]): ... = {
  import c.universe.Apply
  val es = l match {
    case Apply(_, l: List[c.Expr[Int]]) => l
  }
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM