blob: 482ef34f490710688f09b571b5f2b34052282101 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
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:
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. Expected: let var = Expression.");
}
@Override
public double getValue() {
if (parsedExpression == null)
return 0.0;
return parsedExpression.getValue();
}
}
|