2011-04-12 72 views
6

我想将我的scalac插件拆分为多个文件。这听起来很容易,但由于路径依赖类型问题来自import global._系列,所以我没有成功将其解决。将scalac插件拆分为多个文件

这里的莱·斯波的样本插件:

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") 
      } 
     } 
    } 
    } 
} 

我怎么可以把自己的文件ComponentDivByZeroPhase而无需范围import global._

回答

2

你可以为你的组件创建一个单独的类,并在通过全球:

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) = { 
    }  
    } 
} 
3

在斯卡拉重构图书馆,我解决它由具有特质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 
} 

该方案的工作非常适合我。