Skip to content

Instantly share code, notes, and snippets.

@drexin
Last active October 27, 2016 09:41
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drexin/5540251 to your computer and use it in GitHub Desktop.
Save drexin/5540251 to your computer and use it in GitHub Desktop.
macros to get current file and line, inspired by ruby's __FILE__ and __LINE__
import java.io.File
import language.experimental.macros
import scala.reflect.macros.Context
object Macros {
def LINE: Int = macro lineImpl
def lineImpl(c: Context): c.Expr[Int] = {
import c.universe._
val line = Literal(Constant(c.enclosingPosition.line))
c.Expr[Int](line)
}
def FILE: String = macro fileImpl
def fileImpl(c: Context): c.Expr[String] = {
import c.universe._
val absolute = c.enclosingPosition.source.file.file.toURI
val base = new File(".").toURI
val path = Literal(Constant(base.relativize(absolute).getPath))
c.Expr[String](path)
}
}
object Test extends App {
import Macros._
println(s"Printing from line $LINE of file $FILE")
// Printing from line 4 of file core/src/main/scala/Test.scala
}
@nafg
Copy link

nafg commented Apr 23, 2014

This is great. But how can you get it as an implicit parameter?

@cedricbastin
Copy link

your link didn't open but luckily macros seems to be compatible with implicit parameters:
DeliteEPFL/summer-of-lms-2014@e00f0d8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment