4

I am trying to test some subrules in my parser, to check variants. The rule I am checking is an expression rule

expression: expression PLUS expression      # plusExpression
          | expression IS NOT? NULL         # nullExpression
          | columnIdentifier                # columnExpression
          | literal                         # literalExpression
          ;

In the generated the parse, the method signature is:

public final ExpressionContext expression(int _p) throws RecognitionException {

I'm having trouble figuring out what value to pass as the _p argument.

When I check calls to the expression method in the parser, I see 0 being passed. However, when I try to call parser.expression(0) directly, I get a null pointer exception.

What is the recommended way to call this subrule to enable unit testing?

As reference, here is the code for the unit test rig I am trying to write:

private Expression parseExpression( String expressionString ) {

    DataProcessorLexer lexer = new DataProcessorLexer( new ANTLRInputStream( expressionString ) );
    DataProcessorParser parser = new DataProcessorParser( new CommonTokenStream( lexer ) );

    parser.removeErrorListeners();
    parser.addErrorListener( new DiagnosticErrorListener() );

    // Perform the Parse
    ParseTree tree = parser.expression(0);

    ParseTreeWalker walker = new ParseTreeWalker();
    statementWalker = new StatementWalker();
    walker.walk( statementWalker, tree );

    return statementWalker.getExpressionValue( tree );
}
DaveDude
  • 295
  • 2
  • 13
  • 2
    Those labels, `#...`, are, AFAIK, only meant to be used in tree-listener classes. Checkout your BaseListener class that has methods corresponding with your labels. For a demo on how to use a listener, see: http://stackoverflow.com/questions/14667781/antlr-4-and-ast-visitors – Bart Kiers Feb 14 '13 at 23:23
  • I think recursive rules like `expression` are expected to be called from non-recursive rules first. There is some context that a recursive rule needs to reference that apparently only non-recursive ones build. It should be enough to add a rule like `statement : expression;` and call `statement` from your test code instead. – user1201210 Feb 15 '13 at 07:58
  • @tenterhook - that approach works. I can continue with my testing now taking that approach. – DaveDude Feb 15 '13 at 17:35
  • https://github.com/antlr/antlr4/issues/161 – Sam Harwell Feb 19 '13 at 17:06

0 Answers0