This can be achieved with Scala macros , an experimental language feature available from version 2.10.
Macros allow you to interact with the AST building during the parsing phase of the source code and modify the AST trees until the actual compilation is complete.
, Context, String, AST.
. :
, :
import scala.reflect.macros.Context
import scala.language.experimental.macros
object Macros {
def sourceFile: String = macro sourceFileImpl
def sourceFileImpl(c: Context) = {
import c.universe._
c.Expr[String](Literal(Constant(c.enclosingUnit.source.path.toString)))
}
}
, :
object Main extends App {
val fileName = Macros.sourceFile
println(fileName)
}
. , .