I've looked at the documentation of the compiler, and search on the 'Net, but I can't find how to tell the compiler to produce "formatted" backend generated code.

I've read somewhere that you can't debug Nim code directly, but that doesn't mater because you can just debug the generated code. I guess it might be a question of practice, but without any formatting, without original line numbers in comments, without original comments, and without the original Nim code as comments, I find it extremely hard to relate what I see in the nimcache to the code I wrote. This is obviously the default output, which can be compiled to an executable efficiently; nothing wrong with that. But as a human, I honestly can't make sense of this. And other code translation/generation tools I used before always had some (non-default) option to make the generated code "human readable". I guess I could run an automated code formatter on nimcache, but that wouldn't get me far as to the readability, without the original code in comments, and also then the lines in the formatted code would not match the debug info in the executable anymore.

Anyway, my goal atm is not to debug (I'm used to get by with "printf"), but to learn how the compiler converts Nim code to the chosen backend, so that I get a better "feel" for which construct is going to give me the desired result, be it to optimize performance, or memory usage, or to achieve the desired data-alignment in memory.

2017-10-08 10:04:22

Unless you use a lot of templates which inline all the code, I feel like the generated C / C++ code is easily grep-able as name-mangling is just a suffix.

So if you have a function foo, it may be named foo_a12JGoflssgyns, but you can still find it.

An alternative is to use the exportc pragma so there is no name mangling.

Also if you use closures, give them a proper name.

I guess a view of the generated C code would be nice in https://play.nim-lang.org/

2017-10-08 11:14:07

nim c --lineDir:on --embedsrc yourProjectFile

nimc file in the docs describes different useful compiler options. You can also use them in a config file to not provide repeatedly on command line.

2017-10-08 12:14:59

Besides embedsrc, see also https://nim-lang.org/docs/nimc.html#compiler-usage-command-line-switches . The``genMapping`` option may be useful too.

I'm not sure this is what you are asking, but if you want to know how the code generator actually produces the target code, my suggestion is to read compiler/jsgen.nim first, which is the js code generator and is a lot simpler than the c/c++ one (which is divided in various files, the actual pass is in compiler/cgen.nim if I remeber rigth)

2017-10-08 12:37:44
Thanks, everyone! I still have to try the "exportc pragma", but it already looks a lot better.
2017-10-08 14:00:09