benjamn / recast

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

Additional leading/trailing newline when printing constructed node with comment #1280

Open molisani opened 1 year ago

molisani commented 1 year ago

https://gist.github.com/molisani/eb2352b755264eac718cf956bd3ac0f7

The above code snippet will print out the following:

function foo() { return true; }
export { foo };
function bar() { return false; }

However, if you uncomment the line addFixComment(newExport); then the output changes to this:

function foo() { return true; }

// This is some comment added to the new export statement.
export { foo };

function bar() { return false; }

There are additional, unexpected (at least to me) new lines before and after the new statement and its comment(s). I would have expected it to look like this instead:

function foo() { return true; }
// This is some comment added to the new export statement.
export { foo };
function bar() { return false; }

Is there some reason the printer has this behavior, or is this a bug with how comments are rendered? I haven't noticed this behavior in all situations when adding comments to constructed nodes, but it definitely appears in this context.

molisani commented 1 year ago

In this case, since this is a single line being added, the comment and spacing "make sense" but if we added multiple statements, the newline would still be inserted after the first statement:

//// original
line1;
line2;
line3;
//// intended replacement
line1;
// The following lines were altered
newLine2a;
newLine2b;
newLine2c;
line3;
//// actual replacement
line1;

// The following lines were altered
newLine2a;

newLine2b;
newLine2c;
line3;