Skip to content

Nim Cheatsheet#

Resources#

Macro Codegen#

  • dumpTree, dumpAstGen, dumpLisp, dump

  • expandMacros

  • treeRepr, repr, lispRepr

Python
macro myAssert(arg: untyped): untyped =
  echo arg.treeRepr
  • see generated code

    Python
    macro myAssert(arg: untyped): untyped =
    # all node kind identifiers are prefixed with "nnk"
      arg.expectKind nnkInfix
      arg.expectLen 3
      # operator as string literal
      let op  = newLit(" " & arg[0].repr & " ")
      let lhs = arg[1]
      let rhs = arg[2]
    
      result = quote do:
        if not `arg`:
          raise newException(AssertionError,$`lhs` & `op` & $`rhs`)
      echo result.repr
    

  • staticRead & staticExec to read files/process at compile time

  • do notation multiple code blocks to macros https://nim-lang.org/docs/manual_experimental.html#do-notation

  • parseStmt & parseExpr

  • getAst (pass macro or template), quote do: pass statements/expressions, code inside the body of quote can be substituted by surrounding it with backticks.

  • extraction from ast nodes

  • name(x) - name of proc

  • body(x) - body
  • createProcType
  • typeof

Nim Script#

References#

Nim DSL#