Search code examples
javascriptparsingtreejavascript-objectsantlr4

ANTLR4 Javascript get tree


Currently I am busy with parsers and tried ANTLR. I understand the grammar so far and now I wanted to implement it in javascript.

Here is a small but important snippet of my code.

if (selected == "Funktionen") {
      console.log("You selected functions")
      const chars = new antlr4.InputStream(data.stringToLex);
      const lexer = new FunktionLexer(chars);
      const tokens = new antlr4.CommonTokenStream(lexer);
      const parser = new FunktionParser(tokens);
      parser.buildParseTrees = true;
      const tree = parser.start();
      tree.accept(new Visitor());
}

My visitor looks like this

class Visitor {
      visitChildren(ctx) {
        if (!ctx) {
          return;
        }
    
        if (ctx.children) {
          return ctx.children.map(child => {
            if (child.children && child.children.length != 0) {
              return child.accept(this);
            } else {
              return child.getText();
            }
          });
        }
      }
    }

I have oriented myself to this tutorial and everything works. https://github.com/antlr/antlr4/blob/master/doc/javascript-target.md

http://lab.antlr.org/ Just hit on start and u will see what I mean.

The object of my tree I get back from my start() function with a right input looks like this:

enter image description here

The big problem is, I want to get the Tree and output it (at least in console log), like on the official ANTLR lab website.


Solution

  • The big problem is, I want to get the Tree and output it

    The object returned by parser.start() is the tree of your parsed input. You don't need a visitor for this.

    What you mean by "and output it", I do not know. Just print it to your console? That can be done by doing:

    const tree = parser.start();
    
    console.log(tree.toStringTree(parser));
    
    // or if the line above doesn't work, try:
    // console.log(tree.toStringTree());