benjamn / recast

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

`Directive` has incorrect `end` value #1284

Closed skoshx closed 1 year ago

skoshx commented 1 year ago

The end index value of parsed program directives is wrong, when using the babel TS parser. I tried the same with latest @babel/parser and it seems to work fine, so just bumping @babel/parser to latest should fix this issue.

Minimal reproduction:

const code = `
'use client';
function foo() {}
`
const ast2 = parse(code, { parser: babelTsParser })
console.log("Substring: ")
console.log(code.substring(0, ast2.program.directives[0].end))

// This will console.log:
/*
Substring: 
        'use client';
        f
*/

Notice the leading f... In some cases it also becomes func etc.

eventualbuddha commented 1 year ago

I was unable to reproduce this. I ran this code from a file at the root of the recast repo:

const { parse } = require('./lib/parser');
const babelTsParser = require('./parsers/babel-ts');
const code = `
'use client';
function foo() {}
`
const ast2 = parse(code, { parser: babelTsParser })
console.log("Substring: ")
console.log(JSON.stringify(code.substring(0, ast2.program.directives[0].end)))

I got this output:

Substring: 
"\n'use client';"

The version of @babel/parser shown by npm ls is @babel/parser@7.20.5, which is the one pinned in package.json. If you think this is still a problem, can you provide more details about how you reproduced it? Perhaps you could reproduce it in astexplorer.net?