package ch.bfh.parser; import ch.bfh.CalculatorLexer; import ch.bfh.Token; import ch.bfh.exceptions.ParserException; public class StatementParser extends Parser{ String input; ExpressionParser parsedExpression; public void parseStatement(String input){ this.input = input; cl = new CalculatorLexer(); cl.initLexer(input); parsedExpression = null; parse(); } @Override protected void parse() { Token token = cl.nextToken(); String variableName = null; lastToken = null; loop: while (token != null && token.type != Token.EOL) { switch (token.type) { case Token.LET: if (lastToken != null) throw new ParserException("The keyword 'let' cannot be placed anywhere else than at the beginning of an expression."); break; case Token.EQU: if (lastToken == null || lastToken.type != Token.LET || variableName == null) throw new ParserException("The inputted token '=' can only be placed in a variable declaration context (let variable = Expression)."); break; case Token.END: if (lastToken != null) throw new ParserException("The keyword 'exit' cannot be placed anywhere else than at the beginning of an expression."); else System.exit(0); case Token.ID: if (lastToken != null && lastToken.type == Token.LET && variableName == null) { // we are defining a new variable variableName = token.str; token = cl.nextToken(); continue loop; // lastToken value will thus still be 'let' so that we could then parse the '=' token that is supposed to come next correctly. }else if (variableName != null && lastToken != null && lastToken.type != Token.EQU) throw new ParserException("Two consecutive variables ('"+variableName+"' and '"+token.str+"') were found in the declaration context."); // the expression started with a variable -> no definition -> meaning it is an expression default: parsedExpression = new ExpressionParser(cl, token, false); if (lastToken != null && lastToken.type == Token.EQU) // this still need to be put in the variables list variables.put(variableName, parsedExpression); break; } lastToken = token; token = cl.nextToken(); } if (lastToken == null) return; if (lastToken.type == Token.LET || lastToken.type == Token.EQU) throw new ParserException("Incomplete variable declaration"); } @Override public double getValue() { if (parsedExpression == null) return 0.0; return parsedExpression.getValue(); } }