Hi,
I'm trying to add an echo("OK") to the end of a function. Here are the attempts. Could you please advise how to do this?
import macros
# Illegal storage access. (Attempt to read from nil?)
macro addEcho1(s: stmt): stmt =
s.body.add(newCall("echo", newStrLitNode("OK")))
result = s
proc f1() {.addEcho1.} =
let i = 1+2
echo i
# Internal error
macro addEcho2(s: stmt): stmt =
s.body.add(newCall(bindSym"echo", newStrLitNode("OK")))
result = s
proc f2() {.addEcho2.} =
let i = 1+2
echo i
# Illegal storage access. (Attempt to read from nil?)
macro addEcho3(s: stmt): stmt =
s.body.add(parseExpr("echo \"OK\""))
result = s
proc f3() {.addEcho3.} =
let i = 1+2
echo i
# internal error: expr(nkClosedSymChoice); unknown node kind
macro addEcho4(s: stmt): stmt =
s.body.add(newCall(bindsym"write",bindsym"stdout", newStrLitNode("OK\n")))
result = s
proc f4() {.addEcho4.} =
let i = 1+2
echo i
# Illegal storage access. (Attempt to read from nil?)
macro addEcho5(s: stmt): stmt =
s.body.add(parseExpr("stdout.write \"OK\\n\" "))
result = s
proc f5() {.addEcho5.} =
let i = 1+2
echo i
import macros
macro addEcho(s: untyped): stmt =
s.body.add(newCall("echo", newStrLitNode("OK")))
result = s
proc f1() {.addEcho.} =
let i = 1+2
echo i
You have to use untyped because with stmt, Nim seems to create a symbol f1 beforehand and then gets confused about it because you return a proc f1 again with the same signature. This should probably be reported as bug, because it should at least generate a sensible error message.
Thanks, untyped works. However, I don't think that the source of the errors is the duplicated funtion signature, because the following code works and prints 3 twice:
macro addEcho1(s: stmt): stmt =
s.body.add(s.body[1])
result = s
proc f1() {.addEcho1.} =
let i = 1+2
echo i
f1()