Loop unrolling in Boo

time to read 1 min | 180 words

// We create a class for the macro, the class name is
// meaningful, [macro name]Macro allows us to later refer
// to the macro using just [macro name].
// Note that we inherit from AbstractAstMacro
class UnrollMacro(AbstractAstMacro):

	// Here we perform the actual compiler manipulation
	// the compiler hands us a macro statement, and we have
	// to return a statement back, which will replace it.
	override def Expand(macro as MacroStatement) as Statement:
		// define a block of code
		block = Block()
		// extract the second parameter value
		end = cast(IntegerLiteralExpression, macro.Arguments[1]).Value
		for i in range(end):
			// create assignment statement, using the block: trick 
			// and add it to the output
			statements = [|
					$(macro.Arguments[0]) = $i
			// add the original contents of the macro
			// to the output
		return block
And usage:
unroll i, 5:
	print i

Which will produce:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i