Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing in Nim: Is it possible to get the name of a source file at compile time?

I'm planning a project with multiple modules, and I was looking for a nice solution to run all existing unit tests in the project at once. I came up with the following idea: I can run nim --define:testing main.nim and use the following template as a wrapper for all my unit tests.

# located in some general utils module:
template runUnitTests*(code: stmt): stmt =
  when defined(testing):
    echo "Running units test in ..."
    code

This seems to be working well so far.

As a minor tweak, I was wondering if I can actually print out the file name which is calling the runUnitTests template. Is there any reflection mechanism to get the source file name at compile time?

like image 337
bluenote10 Avatar asked Apr 01 '15 18:04

bluenote10


People also ask

What does nim compile to?

Nim connects to the C compilation process in order to compile the C source code that was generated by it. This means that the Nim compiler depends on an external C compiler, such as GCC or Clang. The result of the compilation is an executable that's specific to the CPU architecture and OS it was compiled on.

How do I run a .nim file?

On Linux we can run our program by typing ./helloworld in the terminal, and on Windows we do it by typing helloworld.exe . c is telling Nim to compile the file, and -r is telling it to run it immediately. To see all compiler options, type nim --help in your terminal.

Where is Nimcache?

The default nimcache directory has changed from the current working directory to: $HOME/. cache/nim/<project_name> for Linux and MacOS. $HOME/nimcache/<project_name> for Windows.


2 Answers

instantiationInfo seems to be what you want: http://nim-lang.org/docs/system.html#instantiationInfo,

template filename: string = instantiationInfo().filename

echo filename()
like image 97
def- Avatar answered Oct 03 '22 17:10

def-


The template currentSourcePath from the system module returns the path of the current source by using a special compiler built-in, called instantiationInfo.

In your case, you need to print the locations of callers of your template, which means you'll have to use instantiationInfo directly with its default stack index argument of -1 (meaning one position up in the stack, or the caller):

# located in some general utils module:
template runUnitTests*(code: stmt): stmt =
  when defined(testing):
    echo "Running units test in ", instantiationInfo(-1).filename
    code

It's worth mentioning that the Nim compiler itself uses a similar technique with this module, which get automatically imported in all other modules by applying a switch in nim.cfg:

like image 37
zah Avatar answered Oct 03 '22 18:10

zah