【问题标题】:Scaladoc generation fails when referencing methods generated by annotation macros引用注释宏生成的方法时,Scaladoc 生成失败
【发布时间】:2020-06-07 08:37:09
【问题描述】:

我有两个班级,分别叫它们FooFizzFoo 使用一个名为 expand 的注释宏来为其某些方法创建别名(实际实现比创建别名要多一点,但简单的版本仍然存在以下问题)。为简单起见,假设expand 宏简单地获取注释类中的所有方法,并复制它们,将“Copy”附加到方法名称的末尾,然后将调用转发给原始方法。

我的问题是,如果我在 Foo 上使用 expand 宏,它会创建一个名为 barCopy 的方法 Foo#bar 的副本,当在另一个类 Fizz 中调用 barCopy 时,一切编译但 scaladoc 生成失败,如下所示:

[error] ../src/main/scala/Foo.scala:11: value barCopy is not a member of Foo
[error]     def str = foo.barCopy("hey")
[error]                   ^
[info] No documentation generated with unsuccessful compiler run

如果我删除标记正在复制的方法的 scaladoc (Foo#bar),sbt doc 命令将再次起作用。就好像 scaladoc 生成器在不使用已启用的宏天堂插件的情况下调用编译器的早期阶段,但如果从有问题的方法中删除文档,它会以某种方式工作。

这是expand 宏:

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

@compileTimeOnly("You must enable the macro paradise plugin.")
class expand extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro Impl.impl
}

object Impl {

  def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
    import c.universe._

    val result = annottees map (_.tree) match {
      case (classDef @
        q"""
          $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents {
            $self => ..$stats
          }
        """) :: _ =>

        val copies = for {
            q"def $tname[..$tparams](...$paramss): $tpt = $expr" <- stats
            ident = TermName(tname.toString + "Copy")
        } yield {
            val paramSymbols = paramss.map(_.map(_.name))
            q"def $ident[..$tparams](...$paramss): $tpt = $tname(...$paramSymbols)"
        }
        q"""
            $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self =>
                ..$stats
                ..$copies
            }
        """
        case _ => c.abort(c.enclosingPosition, "Invalid annotation target: not a class")
    }

    c.Expr[Any](result)
  }

}

以及存在于单独项目中的类:

/** This is a class that will have some methods copied. */
@expand class Foo {
    /** Remove this scaladoc comment, and `sbt doc` will run just fine! */
    def bar(value: String) = value
}

/** Another class. */
class Fizz(foo: Foo) {
    /** More scaladoc, nothing wrong here. */
    def str = foo.barCopy("hey")
}

这似乎是一个错误,或者可能是一个缺失的功能,但是有没有一种方法可以为上述类生成 scaladoc 而无需从复制的方法中删除文档?我在 Scala 2.11.8 和 2.12.1 上都试过了。 This 是一个简单的 sbt 项目,它演示了我遇到的问题。

【问题讨论】:

    标签: scala scala-macros scaladoc scala-macro-paradise


    【解决方案1】:

    这是a bug in Scala,在 2.13 中仍然存在。这个问题的要点是,在为 Scaladoc 编译时(与 sbt doc 一样),编译器引入了额外的 DocDef AST 节点来保存 cmets。这些 与 quasiquote 模式匹配。更糟糕的是,它们甚至无法从 scala-reflect API 中看到。

    这是a comment by @driuzz 的摘录,解释了simulacrum 中类似问题的情况:

    [...] 在正常编译过程中,方法可以作为 DefDef 类型使用,即使它们具有被忽略的 scaladoc 注释。 但是在sbt doc 期间,编译器会生成一些不同的 AST。每个具有 scaladoc 注释的方法都被描述为DocDef(comment, DefDef(...)),这导致该宏根本无法识别它们 [...]

    @driuzz 实施的修复是here。这个想法是尝试将 scala-reflect 树转换为他们的 Scala 编译器表示。对于问题中的代码,这意味着定义一些 unwrapDocDef 以帮助从方法中删除文档字符串。

        val result = annottees map (_.tree) match {
          case (classDef @
            q"""
              $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents {
                $self => ..$stats
              }
            """) :: _ =>
    
            // If the outer layer of the Tree is a `DocDef`, peel it back
            val unwrapDocDef = (t: Tree) => {
              import scala.tools.nsc.ast.Trees
    
              if (t.isInstanceOf[Trees#DocDef]) {
                t.asInstanceOf[Trees#DocDef].definition.asInstanceOf[Tree]
              } else {
                t
              }
            }
    
            val copies = for {
                q"def $tname[..$tparams](...$paramss): $tpt = $expr" <- stats.map(unwrapDocDef)
                ident = TermName(tname.toString + "Copy")
            } yield {
                val paramSymbols = paramss.map(_.map(_.name))
                q"def $ident[..$tparams](...$paramss): $tpt = $tname(...$paramSymbols)"
            }
            q"""
                $mods class $tpname[..$tparams] $ctorMods(...$paramss) extends { ..$earlydefns } with ..$parents { $self =>
                    ..$stats
                    ..$copies
                }
            """
            case _ => c.abort(c.enclosingPosition, "Invalid annotation target: not a class")
        }
    

    当然,由于这会从 Scala 编译器导入一些东西,所以 macro 项目的 SBT 定义必须更改:

    lazy val macros = (project in file("macros")).settings(
        name := "macros",
        libraryDependencies ++= Seq(
            "org.scala-lang" % "scala-reflect" % scalaV,
            "org.scala-lang" % "scala-compiler" % scalaV  // new
        )
    ).settings(commonSettings: _*)
    

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多