Recently for a project I had the pleasure to work with the Mozilla sweet.js project. In this post I’ll go through the basics of sweet.js’s case based macros.
So, what is a macro? Macros give you snippets in the programming language that allow you to augment the way the language works. You can think of macros as powerful templates that can expand inline over some matching patterns. Sweet.js support different kind of macros. Let’s quickly explore the differences between a rule base macro and a case based macro.
Rule Based Macros : MACRO > OUTPUT
Our rule base macro definition contain a pattern and a template that is output excactly as it was written inside the macro definition. For example an identity rule bases macro definition will look something like:
Case Based Macros: MACRO > CODE-EXEC > OUTPUT
The main difference is that case based macros execute code before returning the template, meaning they have their own lexical scope and allow for more complex logic. So if we compare with the id rule base macro we saw above, in sweet js we will re-write the id macro as following:
Well this doesn’t show much of the potential of a case base macro, so let’s change this id macro into a randomid macro that will generate a random id;
Macros are very powerful ways to extend the syntax of a language. Learn more about them, and how to use sweet.js: