nim-lang

Nim code parser


There are parsers available in the macros package, like parseExpr and parseStmt but they're {.compileTime.} procs.

Is there any way to parse a string of Nim code at runtime, yielding an AST that can be analyzed?


Solution

  • Yes. Make sure you have a fresh compiler module installed:

    nimble install compiler@0.11.3
    

    Then your code:

    # File: myfile.nim
    import compiler.modules, compiler.ast, compiler.astalgo,
        compiler.passes, compiler.llstream
    
    proc dummyOpen(s: PSym): PPassContext = discard
    proc logASTNode(context: PPassContext, n: PNode): PNode =
      result = n
      debug(n)
    
    proc displayAST*(program: string) =
      var m = makeStdinModule()
      incl(m.flags, sfMainModule)
      registerPass(makePass(open = dummyOpen, process = logASTNode))
      processModule(m, llStreamOpen(program), nil)
    
    displayAST("""
    proc hi() =
      echo "hi"
    """)
    

    Compiling is a bit tricky. You have to point where docutils reside inside your nim lib dir.

    nim c -r --NimblePath:PATH_TO_NIM_LIB/packages/docutils ~/myfile.nim