我想把我的scalac插件分成多个文件。这听起来很简单,但是由于import global._行产生的依赖路径的类型问题,我没有成功地完成它。
下面是Lex Spoon的示例插件:
package localhost
import scala.tools.nsc
import nsc.Global
import nsc.Phase
import nsc.plugins.Plugin
import nsc.plugins.PluginComponent
class DivByZero(val global: Global) extends Plugin {
import global._
val name = "divbyzero"
val description = "checks for division by zero"
val components = List[PluginComponent](Component)
private object Component extends PluginComponent {
val global: DivByZero.this.global.type = DivByZero.this.global
val runsAfter = "refchecks"
// Using the Scala Compiler 2.8.x the runsAfter should be written as below
// val runsAfter = List[String]("refchecks");
val phaseName = DivByZero.this.name
def newPhase(_prev: Phase) = new DivByZeroPhase(_prev)
class DivByZeroPhase(prev: Phase) extends StdPhase(prev) {
override def name = DivByZero.this.name
def apply(unit: CompilationUnit) {
for ( tree @ Apply(Select(rcvr, nme.DIV), List(Literal(Constant(0)))) <- unit.body;
if rcvr.tpe <:< definitions.IntClass.tpe)
{
unit.error(tree.pos, "definitely division by zero")
}
}
}
}
}如何在没有import global._的情况下将Component和DivByZeroPhase放在各自的文件中?
发布于 2011-04-12 09:00:40
这是一个非常老的项目,我做了同样的事情:
如果你不需要从全局变量传递依赖路径的类型,不用担心试图保持它的"this.global“部分的相关性。
发布于 2011-04-12 16:42:21
在Scala重构库中,我通过一个特征CompilerAccess解决了这个问题:
trait CompilerAccess {
val global: tools.nsc.Global
}现在,需要访问global的所有其他特征只需将CompilerAccess声明为依赖项:
trait TreeTraverser {
this: CompilerAccess =>
import global._
...
}然后有一个混合了所有这些特征的类,并提供了一个全局的实例:
trait SomeRefactoring extends TreeTraverser with OtherTrait with MoreTraits {
val global = //wherever you get your global from
}这个计划对我来说效果很好。
发布于 2011-04-12 09:09:52
您可以为您的组件创建一个单独的类,并将global传入:
class TemplateComponent(val global: Global) extends PluginComponent {
import global._
val runsAfter = List[String]("refchecks")
val phaseName = "plugintemplate"
def newPhase(prev: Phase) = new StdPhase(prev) {
override def name = phaseName
def apply(unit:CompilationUnit) = {
}
}
}https://stackoverflow.com/questions/5629127
复制相似问题