/**
* Name: Parser.java
*
* The main objective of this class is to implement a simple parser.
* It should be able to parser the following grammar rule:
*
*
*
*
* The given code is provided to assist you to complete the required tasks. But the
* given code is often incomplete. You have to read and understand the given code
* carefully, before you can apply the code properly. You might need to implement
* additional procedures, such as error checking and handling, in order to apply the
* code properly.
*/
public class Parser {
MyTokenizer _tokenizer;
public Parser(MyTokenizer tokenizer) {
_tokenizer = tokenizer;
}
/*
*/
static Exp parseExp(Tokenizer tok) {
Token cur = tok.current();
if (cur.type() == Token.Type.LBRA) {
tok.next();
Exp exp1 = parseExp(tok) ;
Token operator = tok.current();
tok.next();
Exp exp2 = parseExp(tok);
cur = tok.current();
if (cur.type() == Token.Type.RBRA) throw new Error(“RBRA expected”);
tok.next();
}else if (cur.type() == Token.Type.SUB) {
tok.next();
Exp exp = parseExp(tok);
return new SubExp(exp);
}}
public Exp parseExp() {
// ########## YOUR CODE STARTS HERE ##########
return parseExp(this._tokenizer);
}
//
public Exp parseTerm() {
}
//
public Exp parseFactor() {
}
public static void main(String[] args) {
MyTokenizer mathTokenizer = new MyTokenizer(“2+1”);
Exp t1 = new Parser(mathTokenizer).parseExp();
System.out.println(t1.show());
System.out.println(t1.evaluate());
}
}