Skip to content

Instantly share code, notes, and snippets.

@treeform
Created January 23, 2018 23:11
Show Gist options
  • Save treeform/929915fae3ce5923df69e940d2b657c7 to your computer and use it in GitHub Desktop.
Save treeform/929915fae3ce5923df69e940d2b657c7 to your computer and use it in GitHub Desktop.
import macros
macro print*(n: varargs[typed]): untyped =
result = newNimNode(nnkStmtList, n)
for i in 0..n.len-1:
if n[i].kind == nnkStrLit:
# pure string literals are written diretly
result.add(newCall("write", newIdentNode("stdout"), n[i]))
else:
# other expressions are written in <expression>: <value> syntax
result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i])))
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": ")))
result.add(newCall("write", newIdentNode("stdout"), n[i]))
if i != n.len-1:
# separate by " "
result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(" ")))
else:
# add newline
result.add(newCall("writeLine", newIdentNode("stdout"), newStrLitNode("")))
@treeform
Copy link
Author

I this might solves my problem

macro print*(n: varargs[typed]): untyped =
  var command = nnkCommand.newTree(
    newIdentNode(!"echo")
  )
  for i in 0..n.len-1:
    if n[i].kind == nnkStrLit:
      command.add(n[i])
    else:
      command.add(toStrLit(n[i]))
      command.add(newStrLitNode("="))
      command.add(n[i])
    if i != n.len-1:
      command.add(newStrLitNode(" "))
  return nnkStmtList.newTree(command)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment