Get filename of the current file in scala

守給你的承諾、 提交于 2019-12-05 12:49:57

This can be achieved with Scala macros, an experimental language feature available from version 2.10.

Macros make it possible to interact with the building of the AST during the source code parsing phase, and to modify trees of AST before the actual compilation is performed.

Since the information about the context of the compilation is available to the macro though the Context object, during the parsing phase it is possible to retrieve the source file name and to return it as a String literal, to be inserted in place of the macro call in the AST.

What follows is a working example of returning the source file name. The example is divided in two files:

A source file where the macro is defined and implemented:

// Contents of: "Macros.scala"

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

Another source file where the macro is used:

// Contents of: "Main.scala"

object Main extends App {
    val fileName = Macros.sourceFile
    println(fileName)
}

The macro implementation and the code using it must be in different source files. The file name returned is the correct one, i.e. the name of the source file with macro call.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!