Skip to content

Comments unexpectedly showing up in trailingComments as opposed to leadingComments in some cases. #10230

@rfestag

Description

@rfestag

Bug Report

Current Behavior
@babel/parser does not appear to correctly annotate leading/trailing comments. When the statement before the comment does not have a semi-colon, the comment is treated as a trailing comment instead of a leading comment for the next statement.

Input Code

  • REPL or Repo link if applicable:
    const files = glob.sync(`examples/**/*.{js,jsx}`);

    files.forEach(f => {
      const contents = fs.readFileSync(f).toString()
      const parsed = parser.parse(contents, {
        estree: true,
        sourceType: 'module',
        plugins: ['jsx', 'classProperties']
      })
      this.log(JSON.stringify(parsed, null, 2))
    })

If you place the following code in examples/test.jsx and try to run this code on it, you should find comments attached the the preceeding nodes. Adding semi-colons changes the behavior to the expected behavior:

/**
 * Another class component
 */
export class AnotherClassComponent extends Component {
  render() {
    return <span>{value}</span>
  }
}
AnotherClassComponent.propTypes = {
  value: PropTypes.string.isRequired
}

/**
 * This is the default export
 */
export default A = () => <span>DEFAULT!</span>

Expected behavior/code
The above code should work with or without semi-colons preceding the comment. In fact, as far as I can tell, this AST explorer works as expected with babylon7, which I am assuming should be the same as @babel/parser (although that may be an incorrect assumption on my part).

Babel Configuration (.babelrc, package.json, cli command)
N/A. I'm using @babel/parser directly, and do not have a .babelrc.

Environment

  • Babel version(s): 7.5.0
  • Node/npm version: Node 10/npm 6
  • OS: Manjaro Linux
  • Monorepo: no
  • How you are using Babel: @babel/parser

Metadata

Metadata

Assignees

No one assigned

    Labels

    Has PRarea: commentsoutdatedA closed issue/PR that is archived due to age. Recommended to make a new issuepkg: parser

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions