Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
1.9 kB
2
Indexable
Never
public class Parser {

    private Token symbol;
    private final Lexer lexer;

    public Parser(Lexer lexer){
        this.lexer = lexer;
    }

    //E->T {"+" | "-" T}
    //T->F{"*" | "/"F}
    //F->["-"]S
    //S->cislo | "("E")"


    public int statement(){
        consume();
        return expr();
    }

    //E->T {"+" | "-" T}
    private int expr(){
        int value = mul();

        while (symbol == Token.PLUS || symbol==Token.MINUS){
            Token symbolTemp = symbol;
            consume();
            switch (symbolTemp){
                case PLUS:
                    value += mul();
                case MINUS:
                    value -= mul();
            }
        }
        return value;
    }

    //T->F{"*" | "/"F}
    private int mul(){
        int value = unar();

        while (symbol == Token.MUL || symbol == Token.DIV){
            Token symbolTemp = symbol;
            consume();
            switch (symbolTemp){
                case MUL:
                    value = value * unar();
                case DIV:
                    value = value / unar();
            }
        }
        return value;
    }

    //F->["-"]S
    private int unar(){
        int value = term();

        if (symbol == Token.MINUS){
            return (-1) * (statement());
        }

        return value;
    }


    //S->cislo | "("E")"
    private int term(){
        int value = 0;
        if (symbol == Token.NUMBER){
            value = lexer.getValue();
            consume();
        }
        if (symbol == Token.LPAR){
            value = statement();
            if(symbol != Token.RPAR){
                throw new CalculatorException("Missing right parentheses");
            }
        }
        return value;
    }

    private void match(Token expectedToken){

    }

    private void consume(){
        symbol = lexer.nextToken();
    }
}