concept MacroMacro in category .net

appears as: MacroMacro, The MacroMacro
DSLs in Boo: Domain-Specific Languages in .NET

This is an excerpt from Manning's book DSLs in Boo: Domain-Specific Languages in .NET.

6.4.2. Building macros with the MacroMacro

The Boo compiler can do a lot of stuff for us, so it should come as no surprise that it can help us with building macros. The MacroMacro is an extension to the compiler that makes it simpler to write macros. You don’t need to have a class, inherit from AbstractAstMacro, override methods, and so on. All you need to do is write the code to handle the macro transformation.

Let’s write the unroll macro again, this time using the MacroMacro. Listing 6.11 contains the code.

Listing 6.11. Using the MacroMacro to write the UnrollMacro
# Using the MacroMacro, we don't need a class, # just to define what we want the macro to do macro Unroll2: # extract the second parameter value end = cast(IntegerLiteralExpression, Unroll2.Arguments[1]).Value for i in range(end): # create assignment statement, using the block: # trick and add it to # the output statement = [| block: $(Unroll2.Arguments[0]) = $i |].Body yield statement # add the original contents of the macro # to the output yield Unroll2.Body

As you can see, the main differences between this and listing 6.10 is that the MacroMacro removes the need to create a class. We can also yield the statements directly, instead of gathering them and outputting them in a single batch. Inside the macro block, we can refer to the macro statement using the macro’s name. This means that whenever you see Unroll2 inside the macro in listing 6.11, it refers to the MacroStatement instance that’s passed in to the macro implementation (the MacroMacro creates a MacroStatement variable named Unroll2 behind the scenes).