SimpleJ
SimpleJ

Reputation: 14768

Capture a function call's arguments with sweet.js

I'm trying to write a rule for capturing the expression and arguments of a function call with sweet.js.

Here's my current macro (that fails to match):

macro foo {
    rule {
        ( $fn:expr ($args ...) )
    } => {
        $fn("stuff", $args ...) // pushes "stuff" to the beginning of the arguments
    }
}

And some inputs and expected outputs:

foo(somefn("bar"))

should output:

somefn("stuff", "bar")

and

foo(console.log("bar"))

should output:

console.log("stuff", "bar")

Any assistance would be greatly appreciated.

Upvotes: 0

Views: 131

Answers (1)

timdisney
timdisney

Reputation: 5337

The :expr pattern class is greedy so $fn:expr is matching all of somefn("bar") (since that's an entire expression).

In the case, probably the easiest solution is to use ellipses:

macro foo {
    rule {
        ( $fn ... ($args ...) )
    } => {
        $fn ... ("stuff", $args ...) // pushes "stuff" to the beginning of the arguments
    }
}

Upvotes: 2

Related Questions