Metaprogramming: Slangs, Macros and RakuAST

53.1 EVAL

use MONKEY-SEE-NO-EVAL;          # required pragma for string EVAL
my $code = 'say 6 * 7';
EVAL $code;                      # 42
my &dynamic = EVAL 'sub ($x) { $x ** 2 }';
say dynamic(9);                  # 81

53.2 Macros (Experimental)

The original macro implementation is experimental and limited. RakuAST (a new AST representation for the compiler, in development and usable in newer Rakudo versions with RAKUDO_RAKUAST=1 and in 6.e preview) is the foundation for proper hygienic macros and the next-generation compiler frontend. Check the Rakudo release notes for its current status.

use experimental :macros;
macro twice($expr) { quasi { {{{$expr}}}; {{{$expr}}} } }
twice say 'hi';                  # prints "hi" twice

53.3 Slangs (Sublanguages)

Raku's grammar is itself written in Raku and can be extended at compile time. Slangs modify the language's grammar (e.g., Slang::Tuxic, Slang::SQL, Slang::Roman). The $~MAIN slang variable and the RakuAST APIs give access to the parser.

# Example from the ecosystem: zef install Slang::Roman
# use Slang::Roman; say 0rXII + 0rIII;   # 15

53.4 Other Metaprogramming Tools

MOP (Module 26), trait_mod, .wrap, CALLER::/OUTER::/DYNAMIC:: pseudo-packages, BEGIN blocks for compile-time computation, constant computed at compile time, dynamic code loading with require, and Grammar-based DSLs.