Is there a way to get unmodified / uninterpreted source code (as either string
or AST) of an expression in a macro?
motivation 1: to allow writing logging functions that show exact expression on
left hand side, eg: mylog(1+1) # prints 1+1=2 motivation 2: to allow writing
smart assert function that shows values of expression in assert when it failed,
eg: myassert(1+1==3) #errors with: assert failed: 1+1(=2) == 3(3)
in Nim I wasn't able to make it work with toStrLit as it seems to do
const-folding before it's being passed as AST, so my implementations of mylog
and myassert only work well with runtime expressions that aren't const-folded:
macro mylog(x:typed): typed =
result = newNimNode(nnkStmtList, x)
result.add(newCall("write", newIdentNode("stdout"), toStrLit(x)))
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(":")))
result.add(newCall("writeLine", newIdentNode("stdout"), x))
var x=1
mylog(x+1) # x + 1:2 (OK but I'd rather want exact source code with
spacing eg: `x+1:2`)
mylog(1+1) # 2:2 (not OK, I want: 1+1: 2)
NOTE: In D I had a PR that achieved exactly that:
[https://github.com/dlang/dmd/pull/7821](https://github.com/dlang/dmd/pull/7821)
; you can see further motivations for this feature there.