7

I'm trying to implement an implicit materializer as described here: http://docs.scala-lang.org/overviews/macros/implicits.html

I decided to create a macro that converts a case class from and to a String using quasiquotes for prototyping purposes. For example:

case class User(id: String, name: String)
val foo = User("testid", "foo")

Converting foo to text should result in "testid foo" and vice versa.

Here is the simple trait and its companion object I have created:

trait TextConvertible[T] {
  def convertTo(obj: T): String
  def convertFrom(text: String): T
}

object TextConvertible {
  import language.experimental.macros
  import QuasiTest.materializeTextConvertible_impl
  implicit def materializeTextConvertible[T]: TextConvertible[T] = macro materializeTextConvertible_impl[T]
}

and here is the macro:

object QuasiTest {
  import reflect.macros._

  def materializeTextConvertible_impl[T: c.WeakTypeTag](c: Context): c.Expr[TextConvertible[T]] = {
    import c.universe._
    val tpe = weakTypeOf[T]

    val fields = tpe.declarations.collect {
      case field if field.isMethod && field.asMethod.isCaseAccessor => field.asMethod.accessed
    }

    val strConvertTo = fields.map {
      field => q"obj.$field"
    }.reduce[Tree] {
      case (acc, elem) => q"""$acc + " " + $elem"""
    }

    val strConvertFrom = fields.zipWithIndex map {
      case (field, index) => q"splitted($index)"
    }

    val quasi = q"""
      new TextConvertible[$tpe] {
        def convertTo(obj: $tpe) = $strConvertTo
        def convertFrom(text: String) = {
          val splitted = text.split(" ")
          new $tpe(..$strConvertFrom)
        }
      }
    """

    c.Expr[TextConvertible[T]](quasi)
  }
}

which generates

{
  final class $anon extends TextConvertible[User] {
    def <init>() = {
      super.<init>();
      ()
    };
    def convertTo(obj: User) = obj.id.$plus(" ").$plus(obj.name);
    def convertFrom(text: String) = {
      val splitted = text.split(" ");
      new User(splitted(0), splitted(1))
    }
  };
  new $anon()
}

The generated code looks fine, but yet I get the error value id in class User cannot be accessed in User in compilation while trying to use the macro.

I suspect I am using a wrong type for fields. I tried field.asMethod.accessed.name, but it results in def convertTo(obj: User) = obj.id .$plus(" ").$plus(obj.name ); (note the extra spaces after id and name), which naturally results in the error value id is not a member of User.

What am I doing wrong?

2 Answers 2

3

Ah, figured it out almost immediately after sending my question.

I changed the lines

val fields = tpe.declarations.collect {
  case field if field.isMethod && field.asMethod.isCaseAccessor => field.asMethod.accessed
}

to

val fields = tpe.declarations.collect {
  case field if field.isMethod && field.asMethod.isCaseAccessor => field.name
}

which solved the problem.

2

The field you get with accessed.name has a special suffix attached to it, to avoid naming conflicts.

The special suffix is scala.reflect.api.StandardNames$TermNamesApi.LOCAL_SUFFIX_STRING, which has the value, you guessed it, a space char.

This is quite evil, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.