0

I can't seem to get a match

let function = macro {
  case infix {$name:ident $[=] | _ ($params ...) { $body ...} } => {
    return #{
      $name = function $name ($params ...) {
        console.log($name.name);
        $body ...
      }
    }
  }
}
var add = function (x, y){
  return x+y;
}

SyntaxError: [macro] Macro `function` could not be matched with `() {} ...`
11: var add = function (x, y){
              ^

Macro works fine without var.

I'm aware that 1 non-expr term is allowed in expression position but var $name:ident $[=] doesn't work.

If this is impossible with infix is there another way to match a function statement and capture the name of the function?

pelón
  • 393
  • 2
  • 5

2 Answers2

1

It seems I needed to see my problem from a wider scope. As @timdisney explains above,

var xxx = function () {}

requires a var macro, not a function macro.

// log function calls

    let var = macro {
      case {
        $_ $id = function ($params ...) {$body ...}
      } => {
        return #{
          var $id = function $id ($params ...) { 
            console.log($id.name);
            $body ...
          }
        };
      }
      case { $_ } => { return #{var}; }
    };

The second case is a catch-all that returns function unchanged. It's called an identity rule.

pelón
  • 393
  • 2
  • 5
0

The interaction of infix and var is special. For hygiene reasons infix macros can only see back to the = in a var initializer. I've been thinking about how we could ease up that restriction but nothing concrete yet.

To solve you problem here though you might be able to make a var macro that does the thing you want.

timdisney
  • 5,287
  • 9
  • 35
  • 31
  • Thanks Tim. I found the solution while scouring some of the examples. Simple. Yet a revelation on how to approach macros in the future. – pelón Feb 16 '15 at 18:43