本文整理汇总了Scala中scala.tools.nsc.Global类的典型用法代码示例。如果您正苦于以下问题:Scala Global类的具体用法?Scala Global怎么用?Scala Global使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Global类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: DictionaryCheck
//设置package包名称以及导入依赖的类
package com.oradian.dictionarycheck
import scala.tools.nsc.{Global, Phase}
import scala.tools.nsc.plugins.{Plugin, PluginComponent}
import com.softwaremill.debug.DebugMacros._
class DictionaryCheck(val global: Global) extends Plugin {
override val name = "dictionary-check"
override val components = List[PluginComponent](DictionaryLookup)
override val description = "Raise notifications on blacklisted words"
private[this] var dictionaryPath = "dictionary.txt"
override val optionsHelp = Some(
s""" -P:dictionary-check:input:<dictionary> Dictionary file (default: dictionary.txt)"""
)
override def init(options: List[String], error: String => Unit): Boolean =
options forall { option =>
if (option.startsWith("input:")) {
dictionaryPath = option.substring("input:".length)
true
} else {
error("Unsupported option: " + option)
false
}
}
private[this] object DictionaryLookup extends PluginComponent {
override val runsAfter = List("typer")
override val runsBefore = List("patmat")
override val phaseName = "dictionary-lookup"
val global = DictionaryCheck.this.global
import global._
override def newPhase(prev: Phase): Phase = new StdPhase(prev) {
val dictionary = Dictionary.parse(dictionaryPath)
override def apply(unit: global.CompilationUnit): Unit = {
unit.body foreach {
case t @ q"$mods val $tname: $tpt = $expr" =>
dictionary.get(tname.toString.trim) match {
case Some(DictionaryEntry(_, Level.Info, message)) =>
reporter.info(t.pos, message, false)
case Some(DictionaryEntry(_, Level.Warning, message)) =>
reporter.warning(t.pos, message)
case Some(DictionaryEntry(_, Level.Error, message)) =>
reporter.error(t.pos, message)
case _ =>
}
case _ =>
}
}
}
}
}
示例2: QuerySyntaxPlugin
//设置package包名称以及导入依赖的类
import scala.tools.nsc.Global
import tools.nsc.plugins.{PluginComponent, Plugin}
import tools.nsc.transform.Transform
class QuerySyntaxPlugin(val global: Global) extends Plugin {
val name = "query-syntax-transform"
val description = "Translates query expressions to pure scala OptiQL embedded method calls"
val components = List[PluginComponent](QuerySyntaxComponent)
private object QuerySyntaxComponent extends PluginComponent with Transform {
val runsAfter = List[String]("parser")
override val runsBefore = List[String]("namer")
val phaseName = QuerySyntaxPlugin.this.name
override val optionsHelp = Some(
" -P:"+ name +":option sets some option for this plugin\n"+
"Valid Options:\n------------------\n"+
"debug outputs debug information, including tree browsers as transforms take place\n"+
"enable enable this plugin, by default, it is disabled")
override def processOptions(options: List[String], error: String => Unit) {
super.processOptions(options, error)
//TODO need to process options
}
val global: QuerySyntaxPlugin.this.global.type = QuerySyntaxPlugin.this.global
def newTransformer(unit: global.CompilationUnit) = QuerySyntaxTransformer
object QuerySyntaxTransformer extends global.Transformer {
override def transform(tree: global.Tree) = {
QuerySyntaxComponent.this.global.treeBrowsers.create().browse(tree)
tree
}
}
}
}
示例3: InventoryPluginPhase
//设置package包名称以及导入依赖的类
package autoregister.plugin
import scala.tools.nsc.plugins.PluginComponent
import scala.tools.nsc.{ Global, Phase }
import scala.tools.nsc.transform.TypingTransformers
import scala.tools.nsc.transform.Transform
import Utils._
class InventoryPluginPhase(
val global: Global,
addToRegistry: Value => Unit
)
extends PluginComponent with TypingTransformers with Transform { t =>
import global._
import global.definitions._
val runsAfter = List("typer")
override val runsBefore = List("autoregister:registry")
val phaseName = "autoregister:inventory"
override def newTransformer(unit: CompilationUnit) = new InventoryTransformer(unit)
val register = typeOf[autoregister.annotations.Register].typeSymbol
val objRegister = typeOf[autoregister.annotations.RegisterAllDescendentObjects].typeSymbol
val clsRegister = typeOf[autoregister.annotations.RegisterAllDescendentConcreteClasses].typeSymbol
val cClsRegister = typeOf[autoregister.annotations.RegisterAllDescendentCaseClasses].typeSymbol
class InventoryTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {
implicit class RichString(s: String) {
private val forbiddenPrefix = Seq("akka.", "scala.", "java.", "scalajs.")
def allowed: Boolean = !forbiddenPrefix.exists(s.startsWith(_))
}
def getParents(child: Symbol) = {
val r = child.parentSymbols.filter(_.fullNameString.allowed)
// println(child.fullNameString + " : " + r.mkString(","))
r
}
def process(symbol: Symbol) {
val name = symbol.fullNameString
val path = symbol.associatedFile.path
tree
}
}
}
示例4: RuntimeSettings
//设置package包名称以及导入依赖的类
package autoregister.plugin
import scala.tools.nsc.Global
import scala.tools.nsc.plugins.Plugin
import scala.tools.nsc.plugins.PluginComponent
import scala.reflect.api.Positions
object RuntimeSettings {
val registry = Registry()
}
class RuntimePlugin(global: Global) extends TestPlugin(global, RuntimeSettings.registry) {
// Bad workaround
// TODO Better implementation to serialize & deserialize registry content for incremental compilation
override def init(options: List[String], error: String => Unit): Boolean = {
registry.load("target/.cache_autoregister")
super.init(options, error)
}
}
class TestPlugin(
val global: Global,
val registry: Registry = Registry(),
reporter: (Option[String], Set[String]) => Unit = { case _ => () }
)
extends Plugin {
val name = "autoregister"
val description = "Simplify the building of registry containing a set of specific objects"
val components = List[PluginComponent](
new InventoryPluginPhase(global, registry.+=),
new RegistryPluginPhase(global, () => registry.result, registry.registered, reporter),
new CheckPluginPhase(global, () => { registry.save; registry.checkRest })
)
case class ThrowError(cu: global.CompilationUnit, pos: global.Position, msg: String)
}
示例5: CheckPluginPhase
//设置package包名称以及导入依赖的类
package autoregister.plugin
import scala.tools.nsc.plugins.PluginComponent
import scala.tools.nsc.{ Global, Phase }
import scala.tools.nsc.transform.TypingTransformers
import scala.tools.nsc.transform.Transform
class CheckPluginPhase(
val global: Global,
rest: () => Set[String]
)
extends PluginComponent with TypingTransformers with Transform { t =>
import global._
import global.definitions._
val runsAfter = List("autoregister:registry")
override val runsBefore = List("patmat")
val phaseName = "autoregister:check"
override def newTransformer(unit: CompilationUnit) = {
new CheckTransformer(unit, rest())
}
class CheckTransformer(unit: CompilationUnit, registries: Set[String]) extends TypingTransformer(unit) {
override def transform(tree: Tree): Tree = super.transform(tree) match {
case m @ ModuleDef(_, _, _) =>
m
case _ => tree
}
}
}
示例6: ScalaCompilerPlugin
//设置package包名称以及导入依赖的类
package com.softwaremill
import scala.tools.nsc.{Global, Phase}
import scala.tools.nsc.plugins.{Plugin, PluginComponent}
class ScalaCompilerPlugin(override val global: Global) extends Plugin {
override val name: String = "scala-compiler-plugin"
override val description: String = "scala compiler plugin simple example"
override val components: List[PluginComponent] = List(new ScalaCompilerPluginComponent(global))
}
class ScalaCompilerPluginComponent(val global: Global) extends PluginComponent {
override val phaseName: String = "compiler-plugin-phase"
override val runsAfter: List[String] = List("parser")
override def newPhase(prev: Phase): Phase = new StdPhase(prev) {
override def apply(unit: global.CompilationUnit): Unit = {
global.reporter.echo("implement me ")
}
}
}
示例7: Locator
//设置package包名称以及导入依赖的类
package com.avsystem.scex
package compiler
import com.avsystem.scex.util.MacroUtils
import scala.collection.mutable
import scala.reflect.internal.util._
import scala.reflect.io.AbstractFile
import scala.tools.nsc.Global
import scala.tools.nsc.plugins.Plugin
class Locator(pos: Position) extends Traverser {
var last: Tree = _
def locateIn(root: Tree): Tree = {
this.last = EmptyTree
traverse(root)
this.last
}
override def traverse(t: Tree): Unit = {
t match {
case tt: TypeTree if tt.original != null && includes(tt.pos, tt.original.pos) =>
traverse(tt.original)
case _ =>
if (includes(t.pos, pos)) {
if (!t.pos.isTransparent) last = t
super.traverse(t)
} else t match {
case mdef: MemberDef =>
traverseTrees(mdef.mods.annotations)
case _ =>
}
}
}
private def includes(pos1: Position, pos2: Position) =
(pos1 includes pos2) && pos1.end > pos2.start
}
override protected def loadRoughPluginsList() =
loadAdditionalPlugins() ::: super.loadRoughPluginsList()
// toplevel symbol dropping is implemented based on how it's done in the Scala Presentation Compiler
// (which happens e.g. when a source file is deleted)
private val toplevelSymbolsMap = new mutable.WeakHashMap[AbstractFile, mutable.Set[Symbol]]
override def registerTopLevelSym(sym: Symbol): Unit = {
toplevelSymbolsMap.getOrElseUpdate(sym.sourceFile, new mutable.HashSet) += sym
}
def forgetSymbolsFromSource(file: AbstractFile) = {
val symbols = toplevelSymbolsMap.get(file).map(_.toSet).getOrElse(Set.empty)
symbols.foreach { s =>
//like in: scala.tools.nsc.interactive.Global.filesDeleted
s.owner.info.decls unlink s
}
toplevelSymbolsMap.remove(file)
}
}
示例8: TodoExtraction
//设置package包名称以及导入依赖的类
package forcedtodo.plugin
import forcedtodo.todo
import scala.collection.mutable
import scala.tools.nsc.Global
object TodoExtraction {
def apply(global: Global)(unit: global.CompilationUnit): Seq[(global.Tree, global.AnnotationInfo)] = {
import global._
val todoTypeTag = global.typeTag[todo]
class AnnotationTraverser extends Traverser {
val todos = mutable.ArrayBuffer.empty[(global.Tree, global.AnnotationInfo)]
override def traverse(tree: global.Tree): Unit = {
tree match {
case t: ValOrDefDef ?
t.symbol.annotations.filter(isTodo).foreach(a ? todos += ((tree, a)))
case t: ImplDef ?
t.symbol.annotations.filter(isTodo).foreach(a ? todos += ((tree, a)))
case _ ?
}
super.traverse(tree)
}
def isTodo(anno: AnnotationInfo): Boolean = anno.tpe <:< todoTypeTag.tpe
}
val traverser = new AnnotationTraverser()
traverser.traverse(unit.body)
traverser.todos.toSeq
}
}
示例9: ScalaNubPlugin
//设置package包名称以及导入依赖的类
package scalanub
import java.nio.file.{Files, Paths}
import scala.collection.mutable.ArrayBuffer
import scala.tools.nsc.{Global, Phase}
import scala.tools.nsc.plugins.{Plugin, PluginComponent}
class ScalaNubPlugin(val global: Global) extends Plugin { self =>
import global._
val name = "scalanub"
val description = "Compile to nub"
val components: List[PluginComponent] = List[PluginComponent](Component)
private object Component extends PluginComponent {
override val global: ScalaNubPlugin.this.global.type = ScalaNubPlugin.this.global
override val runsAfter: List[String] = List("typer")
override val phaseName = ScalaNubPlugin.this.description
override def newPhase(prev: Phase): Phase = new ScalaNubPhase(prev)
class ScalaNubPhase(prev: Phase) extends StdPhase(prev) {
override val name = self.name
def apply(unit: CompilationUnit): Unit = {
unit.body.foreach {
case ClassDef(mods, name, tparams, impl) if name.toString == "ScalaNubCode" =>
val code = parseTree(impl)
Files.write(Paths.get("/tmp/ScalaNubCode.nub"), code.map(_.show).mkString("\n").getBytes())
case _ =>
// println("sorry, not supported syntax...")
}
}
def parseTree(tree: Tree): List[NubTrees.Tree] = {
val nubCode: ArrayBuffer[NubTrees.Tree] = ArrayBuffer.empty
val traverser = new Traverser {
override def traverse(tree: Tree): Unit = tree match {
case ValDef(mods, name, tpt, rhs) if mods.isMutable =>
nubCode += NubTrees.Let(name.toString, rhs.toString)
case _ =>
super.traverse(tree)
}
}
traverser.traverse(tree)
nubCode.toList
}
}
}
}
示例10: ScalacCompiler
//设置package包名称以及导入依赖的类
package com.outr.pmc.build.compile
import java.io.File
import com.outr.pmc
import com.outr.pmc.build.compile
import scala.tools.nsc.{Global, Settings}
class ScalacCompiler(implicit val project: pmc.Project) extends compile.Compiler {
def exec(dependencies: => List[File] = jarDependencies.get,
outputDirectory: => File = this.outputDirectory.get): Unit = {
val s = new Settings()
s.bootclasspath.append(dependencies.map(_.getAbsolutePath).mkString(":"))
val out = outputDirectory
out.mkdirs()
s.outdir.value = out.getAbsolutePath
val g = new Global(s)
val run = new g.Run
val sourceFiles = Compiler.findInputFiles(inputDirectories.get).map(_.getAbsolutePath)
logger.info(s"Compiling ${sourceFiles.length} files (${sourceFiles.mkString(", ")}).")
run.compile(sourceFiles)
}
override protected def run(): Unit = exec()
}