File tree Expand file tree Collapse file tree 3 files changed +25
-9
lines changed Expand file tree Collapse file tree 3 files changed +25
-9
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ " sv " : patch
3
+ ---
4
+
5
+ fix: preserve comments when parsing JS AST
Original file line number Diff line number Diff line change @@ -170,3 +170,16 @@ test('integration - simple 2', () => {
170
170
}"
171
171
` ) ;
172
172
} ) ;
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
+ } ) ;
Original file line number Diff line number Diff line change @@ -77,22 +77,20 @@ export function parseScript(content: string): TsEstree.Program {
77
77
78
78
Walker . walk ( ast as TsEstree . Node , null , {
79
79
_ ( commentNode , { next } ) {
80
- let comment = comments . shift ( ) ;
80
+ let comment : TsEstree . Comment ;
81
81
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 ) ;
86
85
}
87
86
88
87
next ( ) ;
89
88
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 ) ;
93
91
94
92
if ( / ^ [ , ) \t ] * $ / . test ( slice ) ) {
95
- commentNode . trailingComments = [ comment ] ;
93
+ commentNode . trailingComments = [ comments . shift ( ) ! ] ;
96
94
}
97
95
}
98
96
}
You can’t perform that action at this time.
0 commit comments