Scala:是否可以使用宏注释来注释类的构造函数字段? (宏观天堂)

问题描述 投票:3回答:1

我试图使用宏注释来注释类的构造函数值。假设实现了一个名为@identity的宏注释,并在类A的类定义中使用如下:

class A(@identity val foo: String, // causes error
        val bar: String) {
@identity val foobar: String = "" // doesn't cause error
}

当只是注释foobar时,一切都编译得很好。但是,当注释foo时,我得到以下编译时错误:

没有伴侣的顶级类只能扩展为同名类或同名同伴中的块

有人可以详细说明这个错误及其发生的原因吗?

scala macros annotations scala-macros scala-macro-paradise
1个回答
2
投票

我怀疑你叫一个宏

  import scala.annotation.{StaticAnnotation, compileTimeOnly}
  import scala.language.experimental.macros
  import scala.reflect.macros.whitebox

  @compileTimeOnly("enable macro paradise to expand macro annotations")
  class identity extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro identity.impl
  }

  object identity {
    def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
      import c.universe._
      println(s"$annottees")
      q"..$annottees"
    }
  }

喜欢

  class A(@identity val foo: String,
          val bar: String) {
    @identity val foobar: String = ""
  }

  object A

然后你有错误

Warning:scalac: List(<paramaccessor> val foo: String = _, class A extends scala.AnyRef {
  <paramaccessor> val foo: String = _;
  <paramaccessor> val bar: String = _;
  def <init>(foo: String, bar: String) = {
    super.<init>();
    ()
  };
  @new identity() val foobar: String = ""
}, object A extends scala.AnyRef {
  def <init>() = {
    super.<init>();
    ()
  }
})
Warning:scalac: 
Warning:scalac: List(<paramaccessor> val foo: String = _, def <init>(foo: String, bar: String) = {
  super.<init>();
  ()
})
Warning:scalac: List(val foobar: String = "")
Error:(8, 12) top-level class with companion can only expand into a block consisting in eponymous companions
  class A(@identity val foo: String,
Error:(8, 12) foo is already defined as value foo
  class A(@identity val foo: String,
Error:(8, 12) foo  is already defined as value foo
  class A(@identity val foo: String,

问题是你拿一个类(可能是伴侣对象)并且不仅返回它们而且返回val foo所以你改变顶级定义的数量/风味被禁止https://docs.scala-lang.org/overviews/macros/annotations.html

顶级扩展必须保留注释的数量,它们的风格和名称,唯一的例外是类可以扩展为同名类加上同名模块,在这种情况下,它们会根据以前的规则自动成为伴随。

例如,如果我们更改宏

   def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
      import c.universe._
      println(s"$annottees")
      q"..${annottees.tail}" // addded tail
    }

然后一切都会编译。

© www.soinside.com 2019 - 2024. All rights reserved.