Alex Rivera | Logout

__FUNC__ macro in Scala 2.10

Asked 2013-01-01T22:08:49.087
9

In Scala 2.9.x, I wrote the func function which gives me back the name of the function where func() is executed like the FUNC C preprocessor macro. I understand that in Scala2.10 I should be able to write something more elegant than throwing an exception to do the job.

How can I do it? Thanks in advance for your help.

object TestMyLog extends App {
    val MatchFunc = """(.+)\(.+""".r

def func(i_level: Int): String = {
    val s_rien = "functionNotFound"
    try {
    throw new Exception()
    } catch {
    case unknwn => unknwn.getStackTrace.toList.apply(i_level).toString match {
            case MatchFunc(funcs) => funcs.split('.').toList.last
        case _ => s_rien
    }
    } finally {
    s_rien      
    }
}

def tracedFunction1 = func(1)
def tracedFunction2 = func(1)

println(tracedFunction1)
assert(tracedFunction1=="tracedFunction1")
println(tracedFunction2)
assert(tracedFunction2=="tracedFunction2")
}
Edit
Report

1 Answer

1

This way you should overload funName for each and every Function's arities: Function1, Function2, etc. Maybe some guru will help?

// define macro
import scala.language.experimental.macros
import scala.reflect.macros.Context
object Macros {
  def funName(xs: Function0[_]) = macro funName_impl
  def funName_impl(c: Context)(xs: c.Expr[Function0[_]]) = { 
    c.literal(xs.tree.children.head.toString.split("\\.").last)
  }
}

// exec (in a next compile run)
def haha: Unit = println("Function name: " + Macros.funName(haha _))
haha
answered 2013-01-02T00:05:53.810

Your Answer