Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bad comment location #562

Open
mamaniv opened this issue Aug 5, 2021 · 1 comment
Open

Bad comment location #562

mamaniv opened this issue Aug 5, 2021 · 1 comment

Comments

@mamaniv
Copy link

mamaniv commented Aug 5, 2021

I'm trying to parse and generate code using acorn and astring and I get the following issue:

I parse this code using acorn:

// comment before
const line = 1; // comment after

and then generate this code using astring:

// comment before
// comment after
const line = 1;

as you can see, "comment after" should be after the line and not before the line.

a working sample app to easily reproduce the issue:

'use strict';
const acorn = require('acorn');
const astring = require('astring');
const astravel = require('astravel');

const sourceCode = `// comment before
const line = 1; // comment after
`;
const comments = [];
const tree = acorn.parse(sourceCode, {
  ecmaVersion: 2020,
  locations: true,
  onComment: comments,
});
astravel.attachComments(tree, comments);
const generatedCode = astring.generate(tree, {comments: true});

console.log(generatedCode);

Versions:

node 14.9
astring 1.7.5
acorn 8.4.1
atravel 0.5.0

Reviewing the code, looks like you write the comments before the statement, even though the location index may be after the statement:

{
  "type": "VariableDeclaration",
  "start": 18,
  "end": 33,
...
  "comments": [
    {
      "type": "Line",
      "value": " comment before",
      "start": 0,
      "end": 17,
      ...
    },
    {
      "type": "Line",
      "value": " comment after",
      "start": 34,
      "end": 50,
      ...
    }
  ]
}

I think you should also consider the locations (start/end) before writing the comments.

Thanks.

@davidbonnet
Copy link
Owner

Hi @mamaniv, thanks for reporting this. The formatting of comments intentionally puts trailing comments on top due to a personal preference. However, I can see how this is confusing and the default behavior could indeed be to follow the current placement of comments as closely as possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants