Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Antlr4 visitor (JavaScript) returns array of udefined

I’m trying to make antlr4 visitor, that will return custom result from my tree. I implemented these functions:

export default class GrammarParserVisitor extends MyGrammarParserVisitor {
  // Visit a parse tree produced by MyGrammarParser#formula.
  visitFormula(ctx) {
    let result = [];

    for (let i = 0; i < ctx.getChildCount(); i++) {
      result.push(this.visit(ctx.getChild(i)));
    }

    return result;
  }

  visitFunction(ctx) {
    let result = [ctx.FUNCTION_NAME().getText()];

    const expressionList = ctx.expression();

    for (let i = 0; i < expressionList.length; i++) {
      console.log("FUNC ARGS", expressionList[i].getText());
      result.push(this.visit(expressionList[i]));
    }

    console.log(result);

    return this.result;
  }

And when i do console.log(result); in visitFunction method i get [ 'IF', [ undefined ], [ [ [Array] ] ], [ [ [Array] ] ] ]

but after visitor returns result i get [ undefined, [ [ [Array] ] ], undefined ]
How to return result form visitor without undefined results?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

grammar part

formula : ST expression EOF;
function
    :   FUNCTION_NAME OPEN_ROUND_BRACKET (expression (COMMA expression)*)? CLOSE_ROUND_BRACKET
    ;

and index.js with input string

const formula = "=IF($I$11=D169,1,0)";
var chars = new InputStream(formula, true);
var lexer = new MyGrammarLexer(chars);
var tokens = new CommonTokenStream(lexer);
var parser = new MyGrammarParser(tokens);
const tree = parser.formula();

const visitor = new GrammarParserVisitor();

let res = visitor.visitFormula(tree);

console.log(tree.toStringTree(parser.ruleNames));
console.log(res);

>Solution :

return this.result;

You’ve never set this.result anywhere, so this will return undefined. I assume you want to return the value of the local result variable (the same one you’re printing on the line before), not some field, so cut the this..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading