sweet.js replace this. with @

79 views Asked by At

I want to replace this. with @ sign like in coffee script. I've write the macro:

macro (@) {
    case { return $a } => { return this.$a }
}

function LogSmth(name) {
    this.name = name;
    console.log(@name);
}

But got

SyntaxError: [macro] Macro `@` could not be matched with `name...`
57:     console.log(@name);

How to fix this?

2

There are 2 answers

1
Anthony Calandra On BEST ANSWER

Allow me to expand on Mike C's answer. What happens if we try and do something just with @ (a common operation is to bind an object to this). One might write: X.bind(@, ...) but this would fail with the above macro. Another possibility is the ability to do this: @['some property with a weird name'], but this would also fail with the above macro.

Here's my version:

macro @ {
  rule { [$x:expr] } => { this[$x] }
  rule { $x:ident } => { this.$x }
  rule {} => { this }
}

This also exposes one useful property about applying rules to macros which is that order matters.

0
Mike Cluck On

Cases have to return a syntax array. So you could fix yours by doing the following:

macro @ {
    case { _ } => { return #{ this. } }
}

Or you could produce this using a simple rule that doesn't use any patterns.

macro @ {
    rule {
    } => {
        this.
    }
}