3

I'm use Scalameta(v1.8.0) annotation to a def declaration:

trait MyTrait {
  @MyDeclDef
  def f2(): Int
}

The annotation class defined just return input, as this:

import scala.meta._

class MyDeclDef extends scala.annotation.StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case defn: Decl.Def =>
        defn
      case _ =>
        println(defn.structure)
        abort("@MyDeclDef most annotate a Decl.Def")
    }
  }
}

some compiler error encounter:

Error:'=' expected but eof found.
def f2(): Unit
Error:illegal start of simple expression
def f2(): Unit

Besides, If I use Decl.Var to var v2: Int it works fine.

How to right annotate a trait def? Thanks

LoranceChen
  • 2,453
  • 2
  • 22
  • 48

1 Answers1

0

I didn't work with scala-meta before and tried your example. It looks like we have to implement this method in the macros. For example, if we specify a default implementation:

class MyDeclDef extends scala.annotation.StaticAnnotation {
  inline def apply(defn: Any): Any = meta {
    defn match {
      case defn: Decl.Def =>
        val q"def $name(): $tpe" = defn
        q"def $name(): $tpe = 1"

we will be able to create an instance of MyTrait and print a value of the f2 method :)

val x = new MyTrait
println(x.f2) // Prints 1

var v2: Int works fine, because it fits to case _ in which we abort the compilation.

arz.freezy
  • 648
  • 1
  • 6
  • 12
  • Your implementation works fine but I hope you can try my example. Besides, If you define `q"def $name(): $tpe"`, it will cause same problem as the question encountered.It seems a bug at [github issue](https://github.com/scalameta/paradise/issues/211) – LoranceChen Jul 02 '17 at 13:48