am stuck while writing a visitor for my antlr program, for an expression like
multiplyingExpression ((PLUS | MINUS) multiplyingExpression)*
i want to get the left part of the expression, get the operator type and the right part of the expression, any help please. this is what i have so far
private double WalkLeft(testGrammerParser.MultiplyingExpressionContext context)
{
return Visit(context.GetRuleContext<testGrammerParser.MultiplyingExpressionContext>(0));
}
private double WalkRight(testGrammerParser.MultiplyingExpressionContext context)
{
return Visit(context.GetRuleContext<testGrammerParser.MultiplyingExpressionContext>(1));
}
and the error am getting is Object reference not set to an instance of an object
.
Thanks in advance.
EDIT
Am more looking of something like this
public Integer visitMulDiv(LabeledExprParser.MulDivContext ctx) {
int left = visit(ctx.expr(0)); // get value of left subexpression
int right = visit(ctx.expr(1)); // get value of right subexpression
if ( ctx.op.getType() == LabeledExprParser.MUL ) return left * right; //check operation type
return left / right; // must be DIV
}
EDIT 2 (grammer)
This is the grammer that am using
grammar testGrammer;
/*
* Parser Rules
*/
compileUnit
: expression + EOF
;
expression
: multiplyingExpression ((PLUS | MINUS) multiplyingExpression)*
;
multiplyingExpression
: powExpression ((TIMES | DIV) powExpression)*
;
powExpression
: atom (POW atom)*
;
atom
: scientific
| variable
| LPAREN expression RPAREN
| func
;
scientific
: number (E number)?
;
func
: funcname LPAREN expression RPAREN
;
funcname
: COS
| TAN
| SIN
| ACOS
| ATAN
| ASIN
| LOG
| LN
;
number
: MINUS? DIGIT + (POINT DIGIT +)?
;
variable
: MINUS? LETTER (LETTER | DIGIT)*
;
COS
: 'cos'
;
SIN
: 'sin'
;
TAN
: 'tan'
;
ACOS
: 'acos'
;
ASIN
: 'asin'
;
ATAN
: 'atan'
;
LN
: 'ln'
;
LOG
: 'log'
;
LPAREN
: '('
;
RPAREN
: ')'
;
PLUS
: '+'
;
MINUS
: '-'
;
TIMES
: '*'
;
DIV
: '/'
;
POINT
: '.'
;
E
: 'e' | 'E'
;
POW
: '^'
;
LETTER
: ('a' .. 'z') | ('A' .. 'Z')
;
DIGIT
: ('0' .. '9')
;
/*
* Lexer Rules
*/
WS
:[ \r\n\t] + -> channel(HIDDEN)
;