Skip to content

Commit d08d260

Browse files
fix: preserve comments when parsing JS AST (#609)
* follow esrap implementation * add test * Create short-chicken-sell.md --------- Co-authored-by: Manuel <[email protected]>
1 parent eeb5719 commit d08d260

File tree

3 files changed

+25
-9
lines changed

3 files changed

+25
-9
lines changed

.changeset/short-chicken-sell.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"sv": patch
3+
---
4+
5+
fix: preserve comments when parsing JS AST

packages/core/tests/utils.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,16 @@ test('integration - simple 2', () => {
170170
}"
171171
`);
172172
});
173+
174+
test('integration - preserves comments', () => {
175+
const code = dedent`
176+
/** @type {string} */
177+
let foo = 'bar';
178+
`;
179+
const ast = parseScript(code);
180+
181+
expect(serializeScript(ast, code)).toMatchInlineSnapshot(`
182+
"/** @type {string} */
183+
let foo = 'bar';"
184+
`);
185+
});

packages/core/tooling/index.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -77,22 +77,20 @@ export function parseScript(content: string): TsEstree.Program {
7777

7878
Walker.walk(ast as TsEstree.Node, null, {
7979
_(commentNode, { next }) {
80-
let comment = comments.shift();
80+
let comment: TsEstree.Comment;
8181

82-
while (comment && comment.start! < commentNode.start!) {
83-
commentNode.leadingComments ??= [];
84-
commentNode.leadingComments.push(comment);
85-
comment = comments.shift();
82+
while (comments[0] && commentNode.start && comments[0].start! < commentNode.start) {
83+
comment = comments.shift()!;
84+
(commentNode.leadingComments ??= []).push(comment);
8685
}
8786

8887
next();
8988

90-
comment = comments.shift();
91-
if (comment) {
92-
const slice = content.slice(commentNode.end, comment.start);
89+
if (comments[0]) {
90+
const slice = content.slice(commentNode.end, comments[0].start);
9391

9492
if (/^[,) \t]*$/.test(slice)) {
95-
commentNode.trailingComments = [comment];
93+
commentNode.trailingComments = [comments.shift()!];
9694
}
9795
}
9896
}

0 commit comments

Comments
 (0)