Debugging code generation

Given that the code is generated behind the scene, it may feel a little awkward when we cannot even see what the generated code will look like. How can we guarantee that the generated code is exactly what we expect after all those interpolations of variables?

Fortunately, there is a package called CodeTracking that can make debugging code generation easier. We will see how it works here.

From the previous section, we should have generated three functions: info!, warning!, and error!. As these are defined as generic functions, we can examine what methods are defined for each. Let's take error! as an example:

In this case, we only have a single method. We can get to the method object itself using the first function:

Once we have a reference of the method object, we can lean on CodeTracking to reveal the source code of the generated function. In particular, we can use the definition function, which takes a method object and returns an expression object. In order to use this function, we also need to load the Revise package. Enough said, let's try the following:

Here, we can clearly see that the variables are interpolated correctly; the logger.level variable is compared with the ERROR constant, and the logging label correctly contains the [ERROR] string.

We can also see that line numbers are included in the output. Since we defined the functions from the REPL, the line numbers are less useful. If we would have generated the functions from a module that is stored in a file, the filename and line number information would be much more interesting.

The line number nodes seem to be a bit too distracting here, though. We can easily remove them using the rmlines function from the MacroTools package:

The MacroTools.postwalk function is used to apply the rmlines function to every node in the abstract syntax tree. The postwalk function is necessary because the rmlines function only works with the current node.

Now that we understand how to do code generation properly, let's turn around and ask ourselves—is code generation really necessary? Are there any other alternatives? Let us see in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.6.194