Is there already or is it possible to have a Scala macro that gives me access to the text of the source? For instance I would like to write code like this:
val list = List(1, 2, 3)
val (text, sum) = (list.sum).withSource{(source, sum) => (source, sum)}
// would return ("list.sum", 6)
(list.sum).withSource{(source, sum) => println(s"$source: $sum"}
// prints list.sum: 6
I was not able to reuse
withSource
directly to just print the source and value and return the value. ThewithSource
macro cannot be utilized from the same object itself (so I cannot just add my slightly modified version of withSource right in that file) and I am not able to callwithSource
from a subclass ofWithSourceHelper
, limiting reuse through inheritance.In case anyone is interested, here is a complement to Senia's answer to just log the value with the source and return the value so the rest of the computation can occur.
I then define it as an implicit conversion on
def p = macro Debug.logValueImpl[T]
. I can then use like this:The funny part is that I can apply it twice:
And it will show me what the
logValueImpl
macro did:It seems to work with other macros as well:
Even more interestingly if I used
showRaw
instead ofshow
I can even see the tree of the expanded macro, which may come handy to figure out how to write other macros.Do you really want a source code or
Tree
is enough?For
Tree
you could useprefix
ofContext
like this:Usage: