This doesn't seem to work.
when compiles(proc hello() = echo "hi"):
proc hello() = echo "hi"
but passing the code into a macro does.
import macros
macro tester(): untyped =
let procDef = nnkProcDef.newTree(
ident("hello"),
newEmptyNode(),
newEmptyNode(),
nnkFormalParams.newTree(
newEmptyNode()
),
newEmptyNode(),
newEmptyNode(),
nnkStmtList.newTree(
nnkCommand.newTree(
newIdentNode("echo"),
newLit("hi")
)
)
)
var whenStmt = nnkWhenStmt.newTree(
nnkElifBranch.newTree(
nnkCall.newTree(
newIdentNode("compiles"),
nnkStmtListExpr.newTree(procDef)
)
)
)
#treeRepr looks identical to the quote do version
#but it will fail
var whenStmt2 = nnkWhenStmt.newTree(
nnkElifBranch.newTree(
nnkCall.newTree(
newIdentNode("compiles"),
nnkStmtListExpr.newTree(procDef)
),
newStmtList(procDef,nnkCommand.newTree(ident"echo",newLit("bye")))
)
)
whenStmt[0].add quote do:
proc hello() =
echo "hi"
echo "bye"
#result = newStmtList(procDef)
result = newStmtList(whenStmt)
echo treeRepr result
echo repr result
echo treeRepr whenStmt2
tester()
hello()
oddly enough if you use whenStmt2 instead of the quote do version proc hello won't exist so that's another problem altogether
By making it anonymous and calling the proc you define:
import macros
when compiles((proc() =
echo "hi"
echo "foo"
echo "bar")()):
proc hello() = echo "hi"
The cleanest way is to wrap it in a block: ... expression:
when compiles((block:
echo "test 1"
echo "test 2")):
discard
My intention was to check to see if a proc hello exists in the current scope that doesn't conflict with the proc I'm about to create.
A simple test call to the proc would do (when compiles(hello()): ...). But then, the compiler would issue an error anyway if there's a conflict with an existing proc, so why bother checking that in custom compile-time code?