javascriptmacrossweet.js

Sweet.js: macro that targets variables before the tokens?


One of the items on my TODO list is creating a fun coding language that 'compiles' to JavaScript. I would like to try out Sweet.js for this, but I'm wondering if it is possible to write a rule that targets keywords that are before the rule?

As an example, let's say you'd want to create a Yoda-styled JavaScript. A source line could look like this:

six var is;

Would be mapped to

var six;

Is this possible using Sweet.js?


Solution

  • Yep, you'll want to use infix macros:

    let var = macro {
        rule infix { $x:ident | is } => {
            var $x;
        }
    }
    
    six var is
    

    If you wanted is to be the macro instead of var the obvious thing would be:

    let is = macro {
        rule infix { $x:ident var | } => {
            var $x;
        }
    }
    

    But this doesn't actually work. The reason it doesn't work is that var is...special. Basically, since var creates a new binder, macros do not get expanded in the identifier positions of var. So when the expander sees var is it tries to create a new bound variable called is instead of expanding the is macro.

    Using the infix var macro should work for you though.