隐式类的Scala宏注释类型检查失败

时间:2015-03-14 19:40:30

标签: scala macros scala-macros

宏示例代码:

package macros
import scala.reflect.macros.whitebox.Context
import scala.language.experimental.macros
import scala.annotation.StaticAnnotation
class Ant extends StaticAnnotation {
    def macroTransform(annottees: Any*): Unit = macro Ant.impl
}
object Ant {
    def impl(c: Context)(annottees: c.Tree*): c.Tree = {
        import c.universe._
        c.internal.enclosingOwner.asType.toType // this line is Ok
        // ! Any commented line below causes the same compilation error
        // c.internal.enclosingOwner.asType.toType.decls
        // c.mirror.staticClass(c.internal.enclosingOwner.fullName + ".A".toString)
        // c.typecheck(annottees.head)
        q"""implicit class A(val v: Int) extends AnyVal { def ask() = println("ok") }"""
    }
}

将whitebox.Context更改为macros.Context或blackbox.Context无效。 使用ImmlicitViewsDisabled = true或withMacrosDisabled = true更改参数无效。

执行示例代码:

package test
import macros.Ant
object Test extends App {
    val a = new A(42)
    a.ask() // Output should be "ok" (not 42)
    // ! removing [implicit] lets code be compiled
    @Ant implicit class A(v: Int) { def ask() = println(v)}
}

因此,删除行 c.typecheck(annottees.head) 和/或单词 隐式 @Ant隐式类A(v:Int) 允许编译代码。 否则编译崩溃并出现错误:

Error:scalac:
no progress in completing object Test: <?>
while compiling: D:\Projects\_Schemee\TestMacro1\src\test\Test.scala
during phase: globalPhase=typer, enteringPhase=namer
library version: version 2.11.6
compiler version: version 2.11.6
reconstructed args: -nobootcp -classpath ...
last tree to typer: Ident(v)
tree position: <unknown>
tree tpe: Int
symbol: value v
symbol definition: v: Int (a TermSymbol)
symbol package: test
symbol owners: value v -> method A -> object Test
call site: method A in object Test in package test
<Cannot read source file>

在最新的IntelliJ下编译。有和没有Sbt。

问题是:如何在隐式类的宏注释中使用类型检查? (或者我错过了什么?)

编辑:

除了在尝试访问enclosingOwner声明或镜像类A“手动”时引起该错误。

Github link

Issue link

1 个答案:

答案 0 :(得分:1)

它看起来像是一个错误或与编译器行为的交互。

最初的例外:

java.lang.NullPointerException
    at xsbt.Dependency$ExtractDependenciesByMemberRefTraverser$$anonfun$1.isDefinedAt(Dependency.scala:142)

那个位置:

      val typeSymbolCollector = new CollectTypeTraverser({
        case tpe if !tpe.typeSymbol.isPackage => tpe.typeSymbol
      })

遍历者有一条评论暗示类似的问题:

/*
 * Some macros appear to contain themselves as original tree.
 * We must check that we don't inspect the same tree over and over.
 * See https://issues.scala-lang.org/browse/SI-8486
 *     https://github.com/sbt/sbt/issues/1237
 *     https://github.com/sbt/sbt/issues/1544
 */