Rust Macros for DSLs, or, Embedding Lisp inside Rust Source
Recently I’ve been experimenting with Rust macros, and I’ve come to the conclusion that they are quite powerful. More powerful than I had previously realised.
Some readers familiar with Rust may think this article is going to be about the relatively recent addition of procedural macros, but actually I’ve done everything using the old macro_rules!
style macros.
As an experiment, let’s try embedding Lisp inside Rust source. So, we’ll write Lisp code inside an rlisp!{}
macro invocation, and the macros will compile it to ordinary Rust. It’s not “real” Lisp, just an alternate syntax for Rust, but this shows that macros are powerful enough to write DSLs with dramatically different syntax.
For the first step, let’s compile a list style function call:
This works, but the obvious problem is that you cannot nest calls. We can fix that easily with a bit of recursion:
We can ditch the multiply fn
by adding explicit operator support to the macro:
This would have to be done by hand for all the other operators too.
What about defining functions? Well, then we have to be a bit careful because of the distinction between items and expressions in Rust. We can’t define a global function in the middle of a print statement. My approach is to have a separate rlisp_expr!
for the subset of rlisp that works in expression context, and make rlisp!
expand to items. That allows us to both define named functions and have anonymous ones in expressions.
Note the use of the $rest
to allow mutliple statements in a single invocation of rlisp. This is a technique called incremental tt munching which enables a lot of complex macro code.
Now we’re really flying, how about let
statements? Again with two forms, one in expression context to create a local binding and one as an item to create a name usable outside of rlisp:
Hopefully my point has been made now, implementing other special forms like flow control is left as an exercise for the reader.
I’m not suggesting that actually using rlisp as I’ve defined it here is a good idea. Rather, I just wanted to show what you can do to define DSLs even with regular macro_rules!
macros. macro_rules!
does have its limits, but procedural macros add a whole new level of flexibility. I think you can really create any DSL you want, with the only restriction being that the input code must meet the loose requirements of Rust macro input (mainly needing balanced delimiters) and the output must be valid Rust code.
Of course, with great power comes greatly unreadable code. I find that reading macro source is hard on the eyes. Overuse of these techniques can easily create a maintenance headache. The Rust compiler does a heroic effort in trying to report macro problems as useful error messages, but often it has to give up and just tell you that something went wrong in a macro.