Nim code parser
Asked Answered
A

1

8

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?

Arlinearlington answered 9/9, 2015 at 19:15 Comment(0)
I
9

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

nimble install [email protected]

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
Infelicitous answered 9/9, 2015 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.