Have ability for visitors to operate in order? #2092
-
I am working on a feature to parse a language, fix it's AST, then regenerate the same tokens back. The CST visitor provided by chevrotain is excellent because it validates the nodes. However it also merges the nodes inside an "MANY > OR" condition. This means it's not trivial to ensure that we process nodes in order. This is needed to ensure that during generation I don't generate nodes out of order. Here is an example // other code...
document = this.RULE("document", () => {
this.MANY(() => {
this.OR([
{ ALT: () => this.SUBRULE(this.blockDeclaration) },
{ ALT: () => this.SUBRULE(this.attribute) },
{ ALT: () => this.SUBRULE(this.comment) }
]);
});
});
// remaining code... This means if I have a visitor like so: document(ctx: any): string {
ctx.blockDeclaration?.forEach((block: CstNode) => this.visit(block));
ctx.attribute?.forEach((attr: CstNode) => this.visit(attr));
ctx.comment?.forEach((comment: CstNode) => this.visit(comment));
return this.result.join("");
} I can't ensure the ordering. I can write some helper to merge all items, sort by their starting line then starting column perhaps. But I am not sure if it covers all cases. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The fix is to wrap your .OR into another rule.
And in your code, iterate thru the children of the subdocument. |
Beta Was this translation helpful? Give feedback.
The fix is to wrap your .OR into another rule.
And in your code, iterate thru the children of the subdocument.