benjamn / recast

JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator
MIT License
4.99k stars 350 forks source link

Printing comments without text coordinates #251

Open juliankrispel opened 8 years ago

juliankrispel commented 8 years ago

Hi @benjamn. As part of this decaf pr I've been investigating how to print comments in relation to nodes, but without any line/column info. Here's how far I've come:

It's technically possible, but only if I attach comments to nodes like blockStatement or program. What then happens is the comment gets inserted at the beginning or at the end of the block, depending on whether the comment is set as leading or trailing. This happens in the printComments function.

As far as I understand it's not currently possible to attach comments directly to nodes.

I'm turning to you because you probably have a better idea of what parts of recast I'd need to touch in order to do this.

Here's a cake as a thank you in advance -> :cake:

benjamn commented 8 years ago

Thanks for looking into it as far as you have!

Quick question before I take a look: do you have any need for creating comments that are not .leading comments? In other words, are you adding any trailing comments, or comments inside empty BlockStatements, or empty function parameter lists? Weird places, I mean.

If .leading comments are good enough for your purposes, then I think the comment-printing code could assume that a Comment node is .leading if it has no .original node, which would at least save you from having to set comment.leading = true by hand.

juliankrispel commented 8 years ago

That was rather quick @benjamn thanks!

I have no pressing need for creating non-leading comments, trying to sort this out step by step :)

flying-sheep commented 8 years ago

hmm, what happens to this?

function foo() {
    return some(stuff)
    // comment
}

won’t this be a trailing comment?