Skip to content

Instantly share code, notes, and snippets.

@gradha
Last active December 31, 2015 09:09
Show Gist options
  • Save gradha/7964832 to your computer and use it in GitHub Desktop.
Save gradha/7964832 to your computer and use it in GitHub Desktop.
Python's with statement implemented in Nimrod
import macros
macro with_closing*(opening, holder: expr, body: stmt): stmt {.immediate.} =
var code = newNimNode(nnkStmtList)
var def = newNimNode(nnkVarSection)
# Create the variable assignment, holder + opening
var idents = newIdentDefs(holder, newEmptyNode())
idents[2] = opening
def.add(idents)
code.add(def)
# Create the try block and insert the body statements.
var tr = newNimNode(nnkTryStmt)
tr.add(body)
# Now create a finally block which invokes close() on the holder.
var fin = newNimNode(nnkFinally)
fin.add(newStmtList(newCall(newIdentNode("close"), holder)))
tr.add(fin)
code.add(tr)
result = newBlockStmt(code)
with_closing(Open("test.txt", fmWrite), f):
f.write("Hey there\n")
f.write("This looks nice!")
echo "Hey"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment