Generate dynamic comments with sweet.js

976 Views Asked by At

How can I transform the following snippet:

let myVar: string = 'test';

To following output:

// type {string}
var myVar = 'test';

using sweetjs?

UPDATE

I'm looking for a way to transform the exact first code snippet to the second one. Including the // type {string} comment.

I Want to use it to create a simple DSL to generate a code to be checked with google closure compiler.

2

There are 2 best solutions below

0
On BEST ANSWER

This should do it:

let let = macro {
    case { _ $name $[:] $type = $init:expr } => {
        var typeStr = unwrapSyntax(#{$type});
        var varStx = makeKeyword("var", #{here});
        varStx.token.leadingComments = [{
            type: "Line",
            value: " type {" + typeStr + "}"
        }];
        letstx $var = [varStx];
        return #{
            $var $name = $init
        }
    }
}
let myVar: string = 'test';

expands to:

// type {string}
var myVar = 'test';
4
On

I'm not sure what you are looking for, but maybe this snippet:

macro m {
    case {_ () } => {
        var x = makeValue(0, #{here});
        x.token.leadingComments = [{
            type: "Line",
            value: " type {string}"
        }];
        return withSyntax ($x = [x]) #{
            $x
        }
    }
}
m()

macro foo {
  rule { $id = $init } => {
    var $id = $init
  }
  rule { $init } => { var myVar = $init }
}

foo "test";

Sadly you cannot output comments without having a token.

OUTPUT

// type {string}
0;
var myVar = 'test';

Also check out this page at heading "Hygiene", its around the 3/4 of the page.

Hope that helps.

UPDATE

Read through some articles saying a simple rule macro should do the job:

macro foo {
  rule { $id = $init } => {
    var $id = $init
  }
  rule { $init } => { var myVar = $init }
}
// type {string}
foo "test";