简体   繁体   中英

get enclosing class instance at macro expansion time

I've just started playing with macros and wanted to implement a macro from this

class Queryable[T] {
 def map[U](p: T => U): Queryable[U] = macro QImpl.map[T, U]
}
object QImpl {
 def map[T: c.WeakTypeTag, U: c.WeakTypeTag]
        (c: Context)
        (p: c.Expr[T => U]): c.Expr[Queryable[U]] = ...
}

So i've came up with the following version:

class Query[T](val value: T) {
  def map[U](func: T => U): Query[U] = macro Qry.map[T, U]
}

object Qry {
  def map[T: c.WeakTypeTag, U: c.WeakTypeTag](c: Context)(func: c.Expr[T => U]): c.Expr[Query[U]] = {
    import c.universe._
    val q"class Query($value) { ..$body }" = c.enclosingClass
    c.Expr[Query[U]](q"new Query($func($value))")
  }
}

But it failes with a MatchError , as i understand enclosingClass captures it's enclosing class at the call site, which in REPL session is a generated module. So how can i extract value field from Query class and pass it to func expression in def macro?

听起来像是在寻找c.prefix

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