antlrantlr4

How to get lexer rules from ctx in visitor?


I need tob uild a nested array using antlr4 visitor (target language JavaScript).

parser.g4:

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

visitor.js:

visitFunction(ctx) {
    console.log("visitFunction", ctx.getText());
    return this.visitChildren(ctx);
}

I need to get each part of function grammar rule as string (for example FUNCTION_NAME), but using ctx.getText() I get every child node also. How I can get only FUNCTION_NAME lexer part string from ctx?


Solution

  • Parser rules and lexer rules are methods of the context instance. So, in your case, the function parser rule:

    function
        :   FUNCTION_NAME OPEN_ROUND_BRACKET (expression (COMMA expression)*)? CLOSE_ROUND_BRACKET
        ;
    
    // just an example of what an expression might look like
    expression
        : expression '*' expression
        | NUMBER
        ;
    

    can be used like this:

    // Let's say the parsed input is: "Q(42)"
    visitFunction(ctx) {
    
      console.log("FUNCTION_NAME: ", ctx.FUNCTION_NAME()); // Q
      
      var expressionList = ctx.expression();
      console.log("NUMBER: ", expressionList[0].NUMBER()); // 42
    
      return this.visitChildren(ctx);
    }