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?
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);
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.
.