In Experimental featuresĀ§
See primary documentation in context for macros
Macros are code-generating routines, that generate code in compile time, before the program is executed. In Raku its use is still experimental and it needs to be turned on via the pragma
use experimental :macros;
Macro processing happens during parsing time. A macro generates an abstract syntax tree, which is grafted into the program syntax tree. quasi
is the routine that performs this task.
use experimental :macros;macro does-nothing();does-nothing; # OUTPUT: Ā«Ā»
Macros are a kind of routine, so they can take arguments in exactly the same way, and act also in almost the same way.
use experimental :macros;macro is-mighty( );say is-mighty "Freija"; # OUTPUT: Ā« "Freija" is mighty!ā¤Ā»
"Almost" accounts for the fact that the argument is inserted as a literal, including the quotes. Please note that we can also eliminate the parentheses for a macro call, following the same rules as a routine. You can use the unquoting construct {{{}}}
to get rid of this kind of thing:
use experimental :macros;macro is-mighty( );say is-mighty "Freija"; # OUTPUT: Ā«Freija is mighty!ā¤Ā»
Since macro expansion happens at parse time, care must be taken when using external variables in them:
use experimental :macros;my ;macro called();say called() ~ " $called times";say called() ~ " $called times"; # OUTPUT: Ā«Called 2 timesā¤Called 2 timesā¤Ā»
Since macros are expanded at parse time, $called
will be the result when runtime starts, which is already 2
, as printed. Initializing $called
with 0, however, will make this print Called 0 times
since that initialization is run after the parse phase, when the macros are expanded.
Macros are terribly useful when complicated, computed initializations need to be done. However, they are still in the experimental nursery for a good reason. Although the features shown above are not very likely to change, anything, even their very presence, might change at any one time depending in necessities, so it would be best to keep them away from production code. Meanwhile, taking a look at this article by Masak as well as 007
, a new macro language, might provide a glimpse into the things to come.