Search code examples
javascriptsweet.js

Generate dynamic comments with sweet.js


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.


Solution

  • 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';