@@ -269,7 +269,7 @@ parser.prototype.parse = function(code, filename) {
269
269
this . length = this . lexer . _input . length ;
270
270
this . innerList = false ;
271
271
this . innerListForm = false ;
272
- const program = this . ast . prepare ( "program" , null , this ) ;
272
+ const program = this . node ( "program" ) ;
273
273
let childs = [ ] ;
274
274
this . next ( ) ;
275
275
while ( this . token != this . EOF ) {
@@ -350,15 +350,53 @@ parser.prototype.error = function(expect) {
350
350
*/
351
351
parser . prototype . node = function ( name ) {
352
352
if ( this . extractDoc ) {
353
+ let docs = null ;
353
354
if ( this . _docIndex < this . _docs . length ) {
354
- const docs = this . _docs . slice ( this . _docIndex ) ;
355
+ docs = this . _docs . slice ( this . _docIndex ) ;
355
356
this . _docIndex = this . _docs . length ;
356
357
if ( this . debug ) {
357
358
console . log ( new Error ( "Append docs on " + name ) ) ;
358
359
console . log ( docs ) ;
359
360
}
360
- return this . ast . prepare ( name , docs , this ) ;
361
361
}
362
+ const node = this . ast . prepare ( name , docs , this ) ;
363
+ /**
364
+ * TOKENS :
365
+ * node1 commentA token commmentB node2 commentC token commentD node3 commentE token
366
+ *
367
+ * AST :
368
+ * structure:S1 [
369
+ * left: node1 ( trail: commentA ),
370
+ * right: structure:S2 [
371
+ * node2 (lead: commentB, trail: commentC),
372
+ * node3 (lead: commentD)
373
+ * ],
374
+ * trail: commentE
375
+ * ]
376
+ *
377
+ * Algorithm :
378
+ *
379
+ * Attach the last comments on parent of current node
380
+ * If a new node is started and the parent has a trailing comment
381
+ * the move it on previous node
382
+ *
383
+ * start S2
384
+ * start node1
385
+ * consume node1 & set commentA as trailingComment on S2
386
+ * start S2
387
+ * S1 has a trailingComment, attach it on node1
388
+ * ...
389
+ * NOTE : As the trailingComment Behavior depends on AST, it will be build on
390
+ * the AST layer - last child node will keep it's trailingComment nodes
391
+ */
392
+ node . preBuild = function ( ) {
393
+ // inject leading comment on current node
394
+ if ( this . _docIndex < this . _docs . length ) {
395
+ node . setTrailingComments ( this . _docs . slice ( this . _docIndex ) ) ;
396
+ this . _docIndex = this . _docs . length ;
397
+ }
398
+ } . bind ( this ) ;
399
+ return node ;
362
400
}
363
401
return this . ast . prepare ( name , null , this ) ;
364
402
} ;
0 commit comments