Question

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?

Was it helpful?

Solution

Sounds like you are looking for c.prefix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top