Reputation: 942
I want to build a simple rule engine using ANTLR's visitor mode, but when it comes with alternative tokens, I get confused how to get which alternative is. Can anyone help me with that?(sorry of my poor English)
grammar RuleExpression;
expression: '(' Operator arg* ')';
arg: STRING|INTEGER|BOOLEAN|expression;
STRING: '"' .+ '"';
INTEGER: [0-9]+;
BOOLEAN: 'true'|'false';
Operator: [a-zA-Z]+[0-9]*;
WS : [ \t\r\n]+ -> skip;
How do know an arg is a STRING or INTEGER or BOOLEAN or expression?
Upvotes: 4
Views: 207
Reputation: 170227
[...] Is there some method which I can use switch statement?
You can inspect the context's start
token type:
@Override
public Object visitArg(RuleExpressionParser.ArgContext ctx) {
switch (ctx.start.getType()) {
case RuleExpressionLexer.STRING:
return ...;
case RuleExpressionLexer.INTEGER:
return ...;
case RuleExpressionLexer.BOOLEAN:
return ...;
default:
// It was an `expression`
return super.visitExpression(ctx.expression());
}
}
Or you could label the arg
alternatives:
arg
: STRING #StringArg
| INTEGER #IntegerArg
| BOOLEAN #BooleanArg
| expression #ExpressionArg
;
which will cause the visitor to have the following methods:
@Override
public T visitStringArg(RuleExpressionParser.StringArgContext ctx) ...
@Override
public T visitIntegerArg(RuleExpressionParser.IntegerArgContext ctx) ...
@Override
public T visitBooleanArg(RuleExpressionParser.BooleanArgContext ctx) ...
@Override
public T visitExpressionArg(RuleExpressionParser.ExpressionArgContext ctx) ...
instead of the single T visitArg(RuleExpressionParser.ArgContext ctx)
method.
Upvotes: 8