Fork me on GitHub

Sweeten your JavaScript

Sweet.js brings hygienic macros from languages like Scheme and Rust to JavaScript. Macros allow you to sweeten the syntax of JavaScript and craft the language you've always wanted.

Wish the function keyword in JavaScript wasn't so long? What if you could define functions with def instead?

Macros let you do this!

Want a better way to make "classy" objects?

Macros can do that too!

Getting sweet.js

Install the sweet.js compiler via npm:


  $ npm install -g sweet.js

Use the sjs binary to compile your sweet.js code:


  $ sjs -o output.js my_sweet_code.js

Sweet.js is still a young project so expect bugs and missing features. If you find a bug, please report it on github.

Writing macros

You can think of macros as functions that take little bits of syntax and convert it to new bits of syntax at compile-time. Macros are created with the macro keyword:


macro id {
  case ($x) => { $x }
}

This can be read as "define a macro named 'id' that matches a single token surrounded by parenthesis and when invoked returns just the matched token".

A pattern name that begin with "$" in the left hand side of the macro definition matches any token and binds it to that name in macro body while everything else matches literally.

A pattern name can be restricted to a particular parse class by using $name:class in which case rather than matching only a single token the pattern matches all the tokens matched by the parse class.


macro m {
  case ($x:expr) => { 
    // ...
  }
}
m (2 + 5 * 10)

For instance:

The commonly used parse classes that have short names are expr (matches an expression), ident (matches an identifier), and lit (matches a literal). The full list is described here.

Repeated patterns can be matched with the ... syntax.


macro m {
  case ($x ...) => { 
    // ...
  }
}
m (1 2 3 4)

A repeated pattern with a separator between each item can be matched by adding (,) between ... and the pattern being repeated.

Repeated groups of patterns can be matched using $().

Macros can match on multiple cases.