Example to parse expression: atom ((PLUS | MINUS) atom)*

Viewed 36

Calculator.g4

grammar calculator;

expression: atom ((PLUS | MINUS) atom)*;

atom: '1';

PLUS: '+';

MINUS: '-';
WS: [ \r\n\t]+ -> skip;

Is there any examples to explain how to parse the pattern atom ((PLUS | MINUS) atom)*

I have searched a lot of blogs teaching how to parse the simple grammars in visitor and listener model. But, none of them show how to parse the pattern like atom ((PLUS | MINUS) atom)*.

What I am confused is the PLUS/MINUS are different, I can use method AllAtom to range over atoms, but there is no method to get the related PLUS/MINUS. There should be a list of PLUS/MINUS, which may be different from each other.

1 Answers

You can accomplish it by slightly rewriting the grammar. I extracted plus/minus into a separate rule.

grammar Calculator;

expression: atom (sign atom)*;

sign: PLUS | MINUS;

atom: '1';

PLUS: '+';

MINUS: '-';

WS: [ \r\n\t]+ -> skip;

And here would be the corresponding listener:

public class Calculator extends CalculatorBaseListener {

    private int accum;
    private char sign;

    @Override
    public void enterAtom(CalculatorParser.AtomContext ctx) {
        int value = Integer.parseInt(ctx.getText());
        switch (sign) {
            case '\0':
                accum = value;
                break;
            case '+':
                accum += value;
                break;
            case '-':
                accum -= value;
                break;
        }
    }

    @Override
    public void enterSign(CalculatorParser.SignContext ctx) {
        sign = ctx.getText().charAt(0);
    }

    @Override
    public void exitExpression(CalculatorParser.ExpressionContext ctx) {
        System.out.println(accum);
    }
}
Related