benjamn / recast

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

Formatting removed from VariableDeclaration when changing it's kind #268

Open nene opened 8 years ago

nene commented 8 years ago

When running the following program:

var recast = require('recast');
var ast = recast.parse(
    'var a = 1,\n' +
    '    b = 2,\n' +
    '    c = 3;'
);
ast.program.body[0].kind = 'let';
console.log(recast.print(ast).code);

I would expect this output:

let a = 1,
    b = 2,
    c = 3;

But instead I get:

let a = 1, b = 2, c = 3;

Somehow changing the kind of a VariableDeclaration removes all the indentation.

However, when I change declarations of VariableDeclaration in all kinds of ways (without changing the number of items), the formatting is preserved correctly.

Interestingly when I add a comment between the declarations, and then change the kind, the formatting is preserved.

acthp commented 7 years ago

In general, it's unclear what will trigger the pretty-printer, and the pretty-printer is limited with respect to matching code style. It would be useful to be able to explicitly preserve the formatting, or inject formatting.

acthp commented 7 years ago

This also moves comments in odd ways, so

var a = 1, // a
    b = 2;

becomes

var // a
    a = 1,
    b = 2;
benjamn commented 7 years ago

We could definitely hack this to work (and I agree there are benefits to avoiding pretty-printing), but I'd like to have a clean/general way to do handle cases like this, where there's a non-identifier token that can change (unlike { or class) but doesn't have its own AST node. Gonna have to think about that some more.

sangm commented 3 years ago

Has this ever been resolved?