有人可以提供最小最小使用當前scala演示編譯器(即scala.tools.nsc.interactive.Global
)的示例,它可以完成以下任務嗎?Scala演示編譯器 - 最小示例
- 編譯單個虛擬源文件(即,不是在文件系統中,但例如
String
) - 檢索來自編譯器
- 所有階段所得到的信息的源文件中傳播的變化編譯器
- 得到進一步的信息可能異步
似乎是在很多波動和我找不到最新的小例子。所以我非常感謝你的幫助。
有人可以提供最小最小使用當前scala演示編譯器(即scala.tools.nsc.interactive.Global
)的示例,它可以完成以下任務嗎?Scala演示編譯器 - 最小示例
String
)似乎是在很多波動和我找不到最新的小例子。所以我非常感謝你的幫助。
也許不正是你所尋找的,但要做到這一點可能是一個辦法:
寫上你要編到一個臨時文件的源,
運行彙編後面添加> output.tmp
(* nix中)操作者的命令,該命令應該輸出的編譯器輸出到文件中,
讀取該文件,並將其加載到內存...
並最後刪除這兩個tmp文件。
我希望這不是唯一的解決方案,但如果沒有別的可能,至少這應該工作...
好,100賞金的一個星期,仍然沒有答案,所以我會自己試試... 編輯非常受歡迎!
表示編譯器的關鍵類是scala.tools.nsc.interactive.Global
。所以要開始,我們需要創建一個編譯器的實例。
import scala.tools.nsc.interactive.Global
class PresentationCompiler { // we want the compiler output to be virtual val target = new VirtualDirectory("", None)
// need to be adjusted in order to work with // sbt. See this question . val settings = new Settings() // output to virtual target settings.outputDirs.setSingleOutput(target)
// can be replaced by a custom instance // of AbstractReporter to gain control. val reporter = new ConsoleReporter(settings)
val compiler = new Global(settings, reporter)
... }
對於設置the link provided by Abhishek是非常有價值的。
但現在最有趣的部分:
1.編譯單個虛擬源文件
要編譯字符串有創造與下面VirtualFile
一個BatchSourceFile
的可能性。 api在這裏標記爲實驗,似乎是不完整的。
def compile(code: String) {
val source = new BatchSourceFile("<virtual>", code)
val response = new Response[Unit]
compiler.askReload(List(source), response)
response.get.left.foreach { _ =>
// success
}
}
2。從編譯器檢索所有階段的結果信息
這是棘手的部分。由於編譯器的多線程特性以及標誌在不同階段的不同含義中重複使用的事實,不可能一次完成所有內容。基本上,您將不得不求助於種類的方法,這些方法記錄在API中。例如:
val tcompletion = new Response[List[global.Member]]
val pos = compiler.ask(() => new OffsetPosition(source, p))
global.askTypeCompletion(pos, tcompletion)
tcompletion.get(5000).get match {
case Left(members) => // do something with members
case Right(e) =>
e.printStackTrace
}
3.傳播到編譯器
這是最有趣的部分源文件中的變化,我想了解這個問題。我真的沒有得到這個,因爲BatchSourceFile
被描述爲內容不隨時間變化的文件。因此需要提供SourceFile
的自定義實現?爲什麼不在interactive
包中。我相信我只是沒有抓到一些東西。
所以我現在的解決方案是再次調用編譯方法。
下面的鏈接可以幫助
https://github.com/twitter/util/blob/master/util-eval/src/main/scala/com/twitter/util/Eval.scala
我認爲它迎合所有你正在尋找的要求。 :)
添加說明 – SSP 2013-10-25 05:36:15
嗨這個鏈接到Eclipse插件可能有助於https://github.com/scala-ide/scala-ide/blob/master/org.scala-ide.sdt.core/src/scala/tools/eclipse /ScalaPresentationCompiler.scala – Iraklis 2013-05-16 13:15:32
@Iraklis這確實是一個有用的鏈接。我之前看過它,但集成了很多特定於eclipse的功能,我不太明白它的意思......我想單獨使用演示編譯器。還有[關於ENSIME的博客文章](http://ensime.blogspot.de/2010/08/building-ide-with-scala-presentation.html),但這確實是過時的。 – 2013-05-16 13:29:14
您可能還想檢查交互式編譯器的測試https://github.com/scala/scala/tree/b380f9ecbe1be8ffaf0f32001e95566747017294/src/interactive/scala/tools/nsc/interactive/tests – Iraklis 2013-05-16 14:14:47