estools / escodegen

ECMAScript code generator
BSD 2-Clause "Simplified" License
2.64k stars 334 forks source link

Attaching inline comments breaks up lines #464

Open StefanBlamberg opened 3 months ago

StefanBlamberg commented 3 months ago

When attaching comments and generating code there seems to be a bug with the placement of inline comments. They always break up the line which can lead to problems, for example when returning objects in strict mode. Lets take this sample code snippet:

function test() {
  "use strict";
  return /** some inline comment */ {
    someFunc: function() {}
  };
}

When parsing it with acorn and then attaching comments with escodegen and generating the code like this:

import { parse } from 'acorn';
import escodegen from '@javascript-obfuscator/escodegen';

const code = `
function test() {
  "use strict";
  return /** some inline comment */ {
    someFunc: function() {}
  };
}
`

const comments = [];
const tokens = [];
const ast = parse(code, {
  ecmaVersion: 'latest',
  ranges: true,
  locations: true,
  onComment: comments,
  onToken: tokens,
})

escodegen.attachComments(ast, comments, tokens);
console.log(escodegen.generate(ast, {comment: true}));

the output is generated as

function test() {
    'use strict';
    return /** some inline comment */
    {
        someFunc: function () {
        }
    };
}

Notice how the curly brace of the object got moved to a new line, which breaks due to the strict mode, similar to this error (https://stackoverflow.com/a/63953324/5843525)

It generally seems to be a problem that inline comments break up code lines in unexpected ways.