I need to make a recursive descent parser that follows the grammar
<program> → <statements>
<statements>→ <statement> | <statement><semi_colon><statements>
<statement> → <ident><assignment_op><expression>
<expression> → <term><term_tail>
<term_tail> → <add_op><term><term_tail> | ε
<term> → <factor> <factor_tail>
<factor_tail> → <mult_op><factor><factor_tail> | ε
<factor> → <left_paren><expression><right_paren> | <ident> | <const>
<const> → any decimal numbers
<ident> → any names conforming to C identifier rules
<assignment_op> → :=
<semi_colon> → ;
<add_operator> → + | -
<mult_operator> → * | /
<left_paren> → (
<right_paren> →)
I have made a lexer that tokenizes input into token type, token string, and token value.
public Token(int type, String token_string, Object value) {
this.type = type;
this.token_string = token_string;
this.value = value;
}
public class TokenType {
public static final int NUMBER=1;
public static final int LEFT_PAR=2;
public static final int RIGHT_PAR=3;
public static final int PLUS=4;
public static final int MINUS=5;
public static final int STAR=6;
public static final int SLASH=7;
public static final int IDENT=8;
public static final int ASSIGN=9;
public static final int SEMI_COLON=10;
}
I am supposed to parse inputs like
operator1 := 200 + 100 *(100 - 200);
operator2 := operator1 + 300 and return the operator's values
However, I am not sure how I could make the parser.
You add
END_OF_TOKENtoTokenType.You define a
Tokenizerclass. It returns aTokenobject by callingget(). For simplicity here it returns theTokenpassed to the constructor.You define a
Parser.Test:
output: