简体   繁体   中英

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:

在此处输入图像描述

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM