jlongster/es6-macros

default arguments as a macro

Opened this issue · 5 comments

It would be nice to figure out how to do default arguments in function declarations.

This won't be too hard! I'm going to start adding more stuff in the next week or two.

nmn commented

Any updates? I'm struggling with the sweet.js syntax these days, or I'd just send some PRs your way.

I've been using this project so far happily and have been working on a few other things. But I can come back and implement some of this stuff in the next week or so :)

Here's a halfway working thing:

let function = macro {
  // Regular named functions
  rule { $name ($params ...) { $body }  } => {
    function $name split_params_comma ($params ...)  { split_params_space $params ... $body }
  }
  // Anon functions
  rule { ($params ...) { $body }  } => {
    function split_params_comma ($params ...)  { split_params_space $params ... $body }
  }
  // Bodyless functions
  rule { $name ($params ...) { }  } => {
    function $name split_params_comma ($params ...)  {}
  }
}

macro split_params_comma {
  rule { $param ... , $rest ... } => {
    remove_param_value $param ... , split_params_comma $rest ...
  }
  rule { $param ... } => {
    remove_param_value $param ...
  }
}

macro split_params_space {
  rule { $param ... , $rest ... } => {
    param_value_to_if $param ...  split_params_space $rest ...
  }
  rule { $param ... } => {
    param_value_to_if $param ...
  }
}

macro remove_param_value {
  rule { $name=$val } => { $name }
  rule { $name } => { $name }
}

macro param_value_to_if {
  rule { $name=$val } => { if (typeof $name == 'undefined') $name = $val; }
  rule { $name } => {  }
}

function Something(Test = 8) { a }

function Something(Test) { a }

function Something(Test, na = 9, ca = 9) { a }

function Something(Test, na = 9, ca = 9) {  }

Can someone figure out why anom fn are failing?