How to check if node is terminal?

57 Views Asked by At

I'm implementing antlr4 visitor with target language JavaScript and I need to check if node is terminal. I was trying to write this code:

import antlr4 from "antlr4";
import MyGrammarParserVisitor from "./gen/MyGrammarParserVisitor.js";

// This class defines a complete generic visitor for a parse tree produced by MyGrammarParser.

export default class GrammarParserVisitor extends MyGrammarParserVisitor {

    result = [];

    isTerminalNode = (node) => {
        if (!node || node.getChildCount() !== 1) {
            return false; // Not a terminal node if it has more than one child or is nullish
        }
        return node.getChild(0) instanceof antlr4.tree.TerminalNodeImpl;
    };

    visitTerm(ctx) {
        if (this.isTerminalNode(ctx)) {
            this.result.push(ctx.getText());
        }
        return this.visitChildren(ctx);
    }

and i got this error:

return node.getChild(0) instanceof antlr4.tree.TerminalNodeImpl;
                                ^

TypeError: Right-hand side of 'instanceof' is not an object

How can I get check if it is a terminal node?

1

There are 1 best solutions below

1
Mike Lischke On

TerminalNode(Impl) is exported directly in the main index, so by importing the antlr4 namespace you can access it directly using antlr4.TerminalNodeImpl.