lundi 3 août 2015

Passing & validating multiple values to Scala macro

So, I am new to macros in Scala and am having some difficulty with my current objective. I have a class that performs Json parsing of case classes. If the given case class has fields that are of type Enumeration, an implicit array of those enumerations needs to be provided when calling the parser.

I want to use a macro to verify the usages of the parser (at compile time), examine the class that is being sent to the parser and verify whether it has enums in it. If it does have enums, I want to verify that the implicit array of enums is not empty.

Here is what I have so far. I'd like to avoid c.eval if possible, so if there is a better way, I am all for it. I keep getting errors about "forgetting to splice a variable" without much more context than that. Am I even on the right track here?

object Macro {
  def compileTimeCheck(tpe: Any, enums: Array[Enumeration]) = macro impl
  def impl(c: Context)(tpe: c.Expr[Any], enums: c.Expr[Array[Enumeration]]) : c.Expr[Any] = {
    import c.universe._
    reify {
      if (c.eval(enums).isEmpty) {
        if (c.eval(tpe).getClass.getDeclaredFields.exists(_.getType.isInstanceOf[Enumeration])) {
          c.abort(c.macroApplication.pos,
            "You must provide an implicit list of enums in this case")
        }
      }
    }
  }
}





Aucun commentaire:

Enregistrer un commentaire