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")
}
Eric Mariacher
  • 341
  • 1
  • 8

3 Answers3

8
import scala.reflect.macros.Context
import scala.language.experimental.macros

def impl(c: Context) = {
  import c.universe._
  c.enclosingMethod match {
    case DefDef(_, name, _, _, _, _) =>
      c.universe.reify(println(c.literal(name.toString).splice))
    case _ => c.abort(c.enclosingPosition, "no enclosing method")
  }
}

scala> def printEnclosingMethod = macro impl
defined term macro printEnclosingMethod: Unit

scala> def foo = printEnclosingMethod
foo: Unit

scala> foo
foo

scala> printEnclosingMethod
<console>:32: error: no enclosing method
              printEnclosingMethod
              ^
kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Eugene Burmako
  • 13,028
  • 1
  • 46
  • 59
4

I'm not sure about doing it without an exception, but you don't actually need to throw/catch the exception to get the stack trace:

(new Exception).getStackTrace.toList
Kristian Domagala
  • 3,686
  • 20
  • 22
  • 1
    You can even get a stacktrace without creating the exception: there's a getStackTrace() method on Thread, so you could do Thread.currentThread().getStackTrace.toList – Christophe Vanfleteren May 29 '13 at 10:07
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
idonnie
  • 1,703
  • 12
  • 11