Skip to content
This repository was archived by the owner on Mar 29, 2023. It is now read-only.

Commit 583f29a

Browse files
committed
glayzzle#194 - implement the trailingComments interception
1 parent 2171cd3 commit 583f29a

File tree

1 file changed

+41
-3
lines changed

1 file changed

+41
-3
lines changed

src/parser.js

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ parser.prototype.parse = function(code, filename) {
269269
this.length = this.lexer._input.length;
270270
this.innerList = false;
271271
this.innerListForm = false;
272-
const program = this.ast.prepare("program", null, this);
272+
const program = this.node("program");
273273
let childs = [];
274274
this.next();
275275
while (this.token != this.EOF) {
@@ -350,15 +350,53 @@ parser.prototype.error = function(expect) {
350350
*/
351351
parser.prototype.node = function(name) {
352352
if (this.extractDoc) {
353+
let docs = null;
353354
if (this._docIndex < this._docs.length) {
354-
const docs = this._docs.slice(this._docIndex);
355+
docs = this._docs.slice(this._docIndex);
355356
this._docIndex = this._docs.length;
356357
if (this.debug) {
357358
console.log(new Error("Append docs on " + name));
358359
console.log(docs);
359360
}
360-
return this.ast.prepare(name, docs, this);
361361
}
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;
362400
}
363401
return this.ast.prepare(name, null, this);
364402
};

0 commit comments

Comments
 (0)