package ch.bfh.parser; import ch.bfh.lexer.CalculatorLexer; import ch.bfh.lexer.Token; 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' can only be placed at the beginning of an expression."); break; case Token.EQU: if (lastToken == null || lastToken.type != Token.LET || variableName == null) throw new ParserException("The token '=' can only be placed in a variable declaration context (let var = Expression)."); break; case Token.END: if (lastToken != null) throw new ParserException("The keyword 'exit' can only be placed 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: if (lastToken == null || lastToken.type == Token.EQU) { 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); }else throw new ParserException("Incomplete variable declaration. Expected: let var = Expression."); 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. Expected: let var = Expression."); } @Override public double getValue() { if (parsedExpression == null) throw new ParserException("Empty statement."); return parsedExpression.getValue(); } }