Frage

I'm experimenting with macro annotations in Scala 2.10.3 using macroparadise 2.0.0-M3. I am trying to understand how to use quasiquotes to generate a companion object to an annotated class. What I have found so far is how to generate a companion object when it has already been declared. It is puzzling that, this is so even with code that always emits the same structure. For example:

import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.Context

class testThing extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro testThing.impl
}

object testThing {
  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._
    val toEmit = c.Expr(q"""
class Thingy(i: Int) {
  def stuff = println(i)
}

object Thingy {
  def apply(x: Int) = new Thingy(x)
}
""")
    annottees.map(_.tree) match {
      case Nil => {
        c.abort(c.enclosingPosition, "No test target")
      }
      case (classDeclaration: ClassDef) :: Nil => {
        println("No companion provided")
        toEmit
      }
      case (classDeclaration: ClassDef) :: (companionDeclaration: ModuleDef) :: Nil => {
        println("Companion provided")
        toEmit
      }
      case _ => c.abort(c.enclosingPosition, "Invalid test target")
    }
  }
}

And here is an example REPL session showing the difference in behavior between pre-declaring a companion object and not doing so:

scala> @testThing class Thingy { }
No companion provided
defined class Thingy

scala> :paste
// Entering paste mode (ctrl-D to finish)

@testThing class Thingy { }
object Thingy { }

// Exiting paste mode, now interpreting.

Companion provided
defined class Thingy
defined module Thingy

scala> 

Am I mistaken in believing that a companion object should be created in both cases? It is stated at http://docs.scala-lang.org/overviews/macros/annotations.html that macro annotations are intended to allow the creation of companion objects. Related to this is Create or extend a companion object, using a macro annotation on the class, which exhibits the creation of a companion object without using quasiquotes.

War es hilfreich?

Lösung

Looks like a REPL-specific bug: https://github.com/scalamacros/paradise/issues/18.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top