一个简单的表达式解析器
下面是解析器的第一个版本。这个解析器可以计算仅由数字、运算符和括号组成的表达式。尽管getToken()方法可以处理变量,但是这个版本并不对变量做任何处理。在读者明白这个简单解析器的工作原理之后,再增加处理变量的功能。
/*
This module contains the recursive descent
parser that does not use variables.
*/
// Exception class for parser errors.
class ParserException extends Exception {
String errStr; // describes the error
public ParserException(String str) {
errStr = str;
}
public String toString() {
return errStr;
}
}
class Parser {
// These are the token types.
final int NONE = 0;
final int DELIMITER = 1;
final int VARIABLE = 2;
final int NUMBER = 3;
// These are the types of syntax errors.
final int SYNTAX = 0;
final int UNBALPARENS = 1;
final int NOEXP = 2;
final int DIVBYZERO = 3;
// This token indicates end-of-expression.
final String EOE = "\0";
private String exp; // refers to expression string
private int expIdx; // current index into the expression
private String token; // holds current token
private int tokType; // holds token's type
// Parser entry point.
public double evaluate(String expstr) throws ParserException
{
double result;
exp = expstr;
expIdx = 0;
getToken();
if(token.equals(EOE))
handleErr(NOEXP); // no expression present
// Parse and evaluate the expression.
result = evalExp2();
if(!token.equals(EOE)) // last token must be EOE
handleErr(SYNTAX);
return result;
}
// Add or subtract two terms.
private double evalExp2() throws ParserException
{
char op;
double result;
double partialResult;
result = evalExp3();
while((op = token.charAt(0)) == '+' || op == '-') {
getToken();
partialResult = evalExp3();
switch(op) {
case '-':
result = result - partialResult;
break;
case '+':
result = result + partialResult;
break;
}
}
return result;
} |