Harder, Better, Faster, Stronger
macro <name> {
rule { <pattern> } => { <template> }
}
macro id {
rule { ($x) } => { $x }
}
id (42)
// compiles to
42
macro def {
rule {
$name ($params ...) { $body ... }
} => {
function $name ($params ...) { $body ...}
}
}
def add (a, b) {
return a + b;
}
function add(a, b) {
return a + b;
}
Classes are in ES6 but I want them now!
class Person {
constructor(name) {
this.name = name;
}
say(msg) {
console.log(this.name + " says: " + msg);
}
}
Simple desugaring:function Person(name) { this.name = name; }
Person.prototype.say = function(msg) {
console.log(this.name + " says: " + msg);
}
macro class {
rule {
$className {
constructor ($cparams ...) {$cbody ...}
$($mname ($mparams ...) {$mbody ...} ) ...
}
} => {
function $className ($cparams ...) {$cbody ...}
$($className.prototype.$mname
= function $mname ($mparams ...) {$mbody ...}; ) ...
}
}
macro <name> {
case { <pattern> } => { <body> }
}
macro id {
case {_ $x } => {
return #{ $x }
}
}
macro m {
case {_ () } => {
return [makeValue(42, #{here})]
}
}
m ()
// --> expands to
42
macro m {
case {_ $x } => {
return withSyntax($y = [makeValue(2, #{here})]) {
return #{$x + $y}
}
}
}
m 1
// --> expands to
1 + 2
let function = macro {
case {_ $name $params { $body ... } } => {
return #{
function $name $params {console.log("Function called...");
$body ...
}
}
}}
long.obj.path = [1, 2, 3];
if (long.obj.path) { console.log(it); } // logs: [1, 2, 3]
let if = macro {
case {
$if_name
($cond ...) {$body ...}
} => {
return withSyntax($it = [makeIdent("it", #{$if_name})]) {
return #{
var $it = $cond ...
if ($it) {
$body ...
}
}
}
}
}
https://github.com/mozilla/sweet.js
npm install -g sweet.js