Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nim code parser

Tags:

nim-lang

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?

like image 689
Lye Fish Avatar asked Sep 09 '15 19:09

Lye Fish


People also ask

How to generate documentation for a given module in Nim?

The Nim compiler includes a command to generate documentation for a given module. Save the code in Listing 1.2 as test.nim somewhere on your file system then execute nim doc test.nim. A test.html file should be produced beside your test.nim file.

Is there a nim profiler for C?

There is a large amount of profilers available for the Nim programming language. This may come as a surprise because Nim is a relatively new language. The fact is that most of these profilers have not been created specifically for Nim but for C. C profilers support Nim applications because Nim compiles to C.

Is there a guide for Nim in action?

This small guide was originally written for Nim in Action. It didn’t end up in the book due to size constraints. Nim in Action is written in a similar style to this guide, check it out for more in-depth information about the Nim programming language. Get 37% off Nim in Action with code fccpicheta .

What is the difference between the nimprof and strutils modules?

The nimprof module is essential in order for the profiler to work. The strutils module defines the Letters set. Each character in the string x is iterated over, if a character is a letter then ab is called, if it’s a number then num is called, and if it’s something else then diff is called.


1 Answers

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
like image 182
uran Avatar answered Oct 16 '22 09:10

uran