Sweet.js: Convert duplicate token appearance

I want to define a sweet macro that converts

{ a, b } # o

in

{ o.a, o.b }

My current attempt

macro (#) {  
  case infix { { $prop:ident (,) ... } | _ $o } => {
    return #{ { $prop: $o.$prop (,) ... } }
  }
}

However, it gives me

SyntaxError: [patterns] Ellipses level does not match in the template

I suspect that I do not understand how it works ..., and it may be necessary to somehow sort through the values $propand build syntax objects for each and somehow connect them, but I do not understand how to do this.

+4
source share
1 answer

The problem is that the syntax expander believes that you are trying to expand $o.$propinstead $prop: $o.$prop. Here's the solution:

macro (#) {  
  rule infix { { $prop:ident (,) ... } | $o:ident } => {
    { $($prop: $o.$prop) (,) ... }
  }
}

Please note that I put the code block in my own block $()to eliminate the ellipse extension.

: var x = { a, b } # o; var x = { a: o.a, b: o.b };.

+3

Source: https://habr.com/ru/post/1627449/


All Articles