Scalameta: Define specific annotations

I want to auto-generate REST API models in Scala using scalameta annotation macros. Specifically given:

@Resource case class User(
@get               id            : Int,
@get @post @patch  name          : String,
@get @post         email         : String,
                   registeredOn  : Long
)

      

I want to generate:

object User {
  case class Get(id: Int, name: String, email: String)
  case class Post(name: String, email: String)
  case class Patch(name: Option[String])
}

trait UserRepo {
  def getAll: Seq[User.Get]
  def get(id: Int): User.Get
  def create(request: User.Post): User.Get
  def replace(id: Int, request: User.Put): User.Get
  def update(id: Int, request: User.Patch): User.Get
  def delete(id: Int): User.Get
}

      

I have something here: https://github.com/pathikrit/metarest

Specifically, I do this:

import scala.collection.immutable.Seq
import scala.collection.mutable
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.meta._

class get extends StaticAnnotation
class put extends StaticAnnotation
class post extends StaticAnnotation
class patch extends StaticAnnotation

@compileTimeOnly("@metarest.Resource not expanded")
class Resource extends StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    val (cls: Defn.Class, companion: Defn.Object) = defn match {
      case Term.Block(Seq(cls: Defn.Class, companion: Defn.Object)) => (cls, companion)
      case cls: Defn.Class => (cls, q"object ${Term.Name(cls.name.value)} {}")
      case _ => abort("@metarest.Resource must annotate a class")
    }

    val paramsWithAnnotation = for {
      Term.Param(mods, name, decltype, default) <- cls.ctor.paramss.flatten
      seenMods = mutable.Set.empty[String]
      modifier <- mods if seenMods.add(modifier.toString)
      (tpe, defArg) <- modifier match {
        case mod"@get" | mod"@put" | mod"@post" => Some(decltype -> default)
        case mod"@patch" =>
          val optDeclType = decltype.collect({case tpe: Type => targ"Option[$tpe]"})
          val defaultArg = default match {
            case Some(term) => q"Some($term)"
            case None => q"None"
          }
          Some(optDeclType -> Some(defaultArg))
        case _ => None
      }
    } yield modifier -> Term.Param(Nil, name, tpe, defArg)

    val models = paramsWithAnnotation
      .groupBy(_._1.toString)
      .map({case (verb, pairs) =>
        val className = Type.Name(verb.stripPrefix("@").capitalize)
        val classParams = pairs.map(_._2)
        q"case class $className[..${cls.tparams}] (..$classParams)"
      })

    val newCompanion = companion.copy(
      templ = companion.templ.copy(stats = Some(
        companion.templ.stats.getOrElse(Nil) ++ models
      ))
    )

    Term.Block(Seq(cls, newCompanion))
  }
}

      

I am unhappy with the following code:

   modifier match {
     case mod"@get" | mod"@put" | mod"@post" => ...
     case mod"@patch" => ...
     case _ => None
   }

      

The above code does "strict" pattern matching in the annotations that I have. Anyway, to reuse the exact annotations I have to match the pattern for them:

class get extends StaticAnnotation
class put extends StaticAnnotation
class post extends StaticAnnotation
class patch extends StaticAnnotation

      

+3


source to share


1 answer


It is possible to replace the string typed annotation mod@get

with an extractor get()

using the reflection bit at runtime (compile time). Furthermore, let's say we also want to allow users to fully qualify the annotation with @metarest.get

or@_root_.metarest.get

All code examples below assume import scala.meta._

. Tree structure @get

, @metarest.get

and @_root_.metarest.get

is equal to

@ mod"@get".structure
res4: String = """ Mod.Annot(Ctor.Ref.Name("get"))
"""
@ mod"@metarest.get".structure
res5: String = """
Mod.Annot(Ctor.Ref.Select(Term.Name("metarest"), Ctor.Ref.Name("get")))
"""
@ mod"@_root_.metarest.get".structure
res6: String = """
Mod.Annot(Ctor.Ref.Select(Term.Select(Term.Name("_root_"), Term.Name("metarest")), Ctor.Ref.Name("get")))
"""

      

Selectors are either Ctor.Ref.Select

or Term.Select

, and names are either Term.Name

or Ctor.Ref.Name

.

First create a custom selector extractor

object Select {
  def unapply(tree: Tree): Option[(Term, Name)] = tree match {
    case Term.Select(a, b) => Some(a -> b)
    case Ctor.Ref.Select(a, b) => Some(a -> b)
    case _ => None
  }
}

      

Then create some helper utilities

object ParamAnnotation {
  /* isSuffix(c, a.b.c) // true
   * isSuffix(b.c, a.b.c) // true
   * isSuffix(a.b.c, a.b.c) // true
   * isSuffix(_root_.a.b.c, a.b.c) // true
   * isSuffix(d.c, a.b.c) // false
   */
  def isSuffix(maybeSuffix: Term, fullName: Term): Boolean =
    (maybeSuffix, fullName) match {
      case (a: Name, b: Name) => a.value == b.value
      case (Select(q"_root_", a), b: Name) => a.value == b.value
      case (a: Name, Select(_, b)) => a.value == b.value
      case (Select(aRest, a), Select(bRest, b)) =>
        a.value == b.value && isSuffix(aRest, bRest)
      case _ => false
    }

  // Returns true if `mod` matches the tree structure of `@T`
  def modMatchesType[T: ClassTag](mod: Mod): Boolean = mod match {
    case Mod.Annot(term: Term.Ref) =>
      isSuffix(term, termRefForType[T])
    case _ => false
  }

  // Parses `T.getClass.getName` into a Term.Ref
  // Uses runtime reflection, but this happens only at compile time.
  def termRefForType[T](implicit ev: ClassTag[T]): Term.Ref =
    ev.runtimeClass.getName.parse[Term].get.asInstanceOf[Term.Ref]
}

      

With this setting, we can add a companion object to the definition get

using the unapply

boolean extractor



class get extends StaticAnnotation
object get {
  def unapply(mod: Mod): Boolean = ParamAnnotation.modMatchesType[get](mod)
}

      

Doing the same for post

and put

, we can now write

// before
case mod"@get" | mod"@put" | mod"@post" => Some(decltype -> default)
// after
case get() | put() | post() => Some(decltype -> default)

      

Please note that this approach will still not work if the user renames, for example get

on import

import metarest.{get => GET}

      

I would recommend aborting if the annotation is not as expected

// before
case _ => None
// after
case unexpected => abort("Unexpected modifier $unexpected. Expected one of: put, get post")

      

PS. The part object get { def unapply(mod: Mod): Boolean = ... }

is a template that can be generated by some macro @ParamAnnotation

, for example@ParamAnnotion class get extends StaticAnnotation

+3


source







All Articles