2015-05-18 35 views
4

在編譯時,如何在scala 2.11中檢索當前源文件的名稱(編寫代碼的位置)?如何在Scala 2.11中找到封裝源文件的名稱2.11

+0

您需要什麼呢? 假設你有一些宏將把這個字符串粘貼到你想要的位置,它將在.class文件中。在辛格頓的sturtup上評估一次名字不是一個性能殺手。 –

+0

當然,但是由於這些信息對編譯器來說顯然是可用的,並且它是一個常量,所以用宏檢索它似乎更加「正確」。它仍然可以使用這個:http://stackoverflow.com/a/21893197/1670894但顯然它已被scala 2.11棄用。 –

+0

你想要一個名爲'CompilationUnit'的類的對象。我在編譯器插件中使用過它,但不太清楚如何獲取它,或者即使可以從宏中獲取它。 (可能==容易,你可以將這些對象轉換成它們的內部編譯器表示,這是一個令人討厭的任務,它使得quit寫了一些有趣的宏)。 – pedrofurla

回答

4

在REPL,名字是控制檯,但是這表明一個立場知道它的來源。

scala> import scala.language.experimental.macros 
import scala.language.experimental.macros 

scala> import scala.reflect.macros.whitebox.Context 
import scala.reflect.macros.whitebox.Context 

scala> def f(c: Context): c.Tree = { import c._,universe._ ; Literal(Constant(c.enclosingPosition.source.file.name)) } 
f: (c: scala.reflect.macros.whitebox.Context)c.Tree 

scala> def g: String = macro f 
defined term macro g: String 

scala> g 
res0: String = <console> 
+2

'c.macroApplication.pos.source.file.name' –

5

下面是實際執行的伎倆一個有點哈克的方式:

val srcFile = new Exception().getStackTrace.head.getFileName 
println(srcFile) 

來源:How do I get the current script or class name in Scala?

+1

+1爲務實的解決方案。人們可以依賴那些信息嗎? - 我的意思是,如果在編譯期間關閉調試信息會怎麼樣? – Madoc

0

或者,你可以使用@李 - 好易通的優秀sourcecode macro library

def foo(arg: String)(implicit file: sourcecode.File) = { 
    println(s"this file is: '${file.getAbsolutePath}'") 
} 

foo("hello") // "this file is '/path/to/file'" 

另外,很多其他東西一樣行號,變量名稱等