Julia Programming - Metaprogramming

Metaprogramming may be defined as the programming in which we write Julia code to process and modify Julia code. With the help of Julia metaprogramming tools, one can write Julia programming code that modifies other parts of the source code file. These tools can even control when the modified code runs.

Following are the execution stages of raw source code −

Stage 1 − Raw Julia code is parsed

In this stage the raw Julia code is converted into a form suitable for evaluation. The output of this stage is AST i.e. Abstract Syntax Tree. AST is a structure which contains all the code in an easy to manipulate format.

Stage 2 − Parsed Julia code is executed

In this stage, the evaluated Julia code is executed. When we type code in REPL and press Return the two stages happens but they happen so quickly that we don’t even notice. But with metaprogramming tools we can access the Julia code between two stages, i.e. after code parsed but before its evaluation.

Quoted expressions

As we discussed, with metaprogramming we can access the Julia code between two stages. For this, Julia has ‘:’ colon prefix operator. With the help of colon operator, Julia store an unevaluated but parsed expression.


   julia> ABC = 100
   julia> :ABC

Here, − ABC is quoted or unevaluated symbol for Julia i.e. ‘ABC ‘ is an unevaluated symbol rather than having the value 100.

We can quote the whole expressions as below −

julia> :(100-50)
:(100 - 50)

Alternatively, we can also use quote…end keywords to enclose and quote an expression as follows −

julia> quote
         100 - 50
   #= REPL[43]:2 =#
   100 - 50
Check this also:
julia> expression = quote
         for x = 1:5
   #= REPL[46]:2 =#
   for x = 1:5
      #= REPL[46]:3 =#

julia> typeof(expression)

It shows that expression object is parsed, primed and ready to use.

Evaluated expressions

Once you parsed the expression, there is a way to evaluate the expression also. We can use the function eval() for this purpose as follows −

julia> eval(:ABC)

julia> eval(:(100-50))


julia> eval(expression)

In the example, we have evaluated the expressions parsed in above section.

The Abstract Syntax Tree (AST)

As discussed above, Abstract Syntax Tree (AST) is a structure which contains all the code in an easy to manipulate format. It is the output of stage1. It allows us to easily process and modify the Julia code. We can visualize the hierarchical nature of an expression with the help of dump() function.


julia> dump(:(1 * cos(pi/2)))
   head: Symbol call
   args: Array{Any}((3,))
      1: Symbol *
      2: Int64 1
      3: Expr
         head: Symbol call
         args: Array{Any}((2,))
            1: Symbol cos
            2: Expr
               head: Symbol call
               args: Array{Any}((3,))
                  1: Symbol /
                  2: Symbol pi
                  3: Int64 2

Expression interpolation

Any Julia code which has string or expression is usually unevaluated but with the help of dollar ($) sign (string interpolation operator), we can evaluate some of the code. The Julia code will be evaluated and inserts the resulting value into the string when the string interpolation operator is used inside a string.


julia> "the cosine of 1 is $(cos(1))"
"the cosine of 1 is 0.5403023058681398"

Similarly, we can use this string interpolation operator to include the results of executing Julia code interpolated into unevaluated expression −

julia> quote ABC = $(cos(1) + tan(1)); end
   #= REPL[54]:1 =#
   ABC = 2.097710030523042


We are now aware of creating and handling unevaluated expressions. In this section, we will understand how we can modify them. Julia provides macro that accepts an unevaluated expression as input and generates a new output expression.

If we talk about its working, Julia first parses and evaluates the macro, and then the processed code produced by macro will be evaluated like an ordinary expression.

The syntax of defining a macro is very similar to that of a function. Following is the definition of macro that will print out the contents of the things we pass to it −

julia> macro x(n)
            if typeof(n) == Expr
            return n
@x (macro with 1 method)

We can run the macros by preceding the name of the macro with the @ prefix −

julia> @x 500

julia> @x "Tutorialspoint.com"

eval() and @eval

Julia has eval() function and a macro called @eval. Let us see example to know their differences −

julia> ABC = :(100 + 50)
:(100 + 50)

julia> eval(ABC)

The above output shows that the eval() function expands the expression and evaluates it.

julia> @eval ABC
:(100 + 50)

julia> @eval $(ABC)

It can also be treated as follows −

julia> @eval $(ABC) == eval(ABC)

Expanding Macros

The macroexpand() function returns the expanded format (used by the Julia compiler before it is finally executed) of the specified macro.


julia> macroexpand(Main, quote @p 1 + 4 - 6 * 7 / 8 % 9 end)
Any[:-, :(1 + 4), :(((6 * 7) / 8) % 9)]
   #= REPL[69]:1 =#
   (1 + 4) - ((6 * 7) / 8) % 9
Kickstart Your Career

Get certified by completing the course

Get Started