Search code examples
javascriptmacrossweet.js

Can Sweet.js output to comments?


The title to this question answers it all.

I was hoping there was a way to do this, but i am finding it very hard. As of right now, this is what i have tried.

macro statement {
    rule { "$x" } => {
        // @statement $x
    }
}

statement "my/qualified/path"

That did not work :*(

So then i tried this.

macro statement {
    rule { "$x" } => {
        \\ @statement $x
    }
}

macro \ { rule { } => { / }

Clearly, as i thought it would, it results into a syntax error. Is there anyway to make sweetjs output to comments?


Solution

  • The way esprima/escodegen (which sweet.js is built on top of) handles comments is by adding them as properties to existing tokens; comments are not proper tokens in themselves. This means that you cannot output "just" a comment, it must be attached to another token. So if you just add another token after the comment in your macro it will all work:

    macro statement {
        rule { "$x" } => {
            // @statement $x
            42
        }
    }
    

    If you need more flexibility in determining the exact value of a token you can also use case macros and the leadingComments property on the token:

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