Official problem:
Write Java method to perform recursive descent parse of the following production:
<repeat_statement> -> REPEAT <statement> UNTIL <expression> ;
This is what I've come up with:
void repeatStatement() {
if(token == REPEAT) {
token = getNextToken();
if(parseStatement()) {
if(token == UNTIL) {
token = getNextToken();
if(parseExpression()) {
if(token == ;) {
return true
}
}
}
} return false
}
I'm pretty confident that I have the general idea here, but I was hoping that someone could help me polish this/ confirm that I'm on the right track.
1 Answer 1
It looks (vaguely) like you're trying to evaluate the repeat statement. That's not what recursive descent parsing does. I'd expect something like this (in pseudocode):
RepeatStatement repeat_statement() throws ParseException {
if (!consume("REPEAT")) {
throw new ParseException("no REPEAT token");
}
Statement statement = statement();
if (!consume("UNTIL")) {
throw new ParseException("no UNTILtoken");
}
Expression expression = expression();
if (!consume(";")) {
throw new ParseException("no closing semicolon");
}
return new RepeatStatement(statement, expression);
}
answered Jan 29, 2012 at 20:52
Ted Hopp
235k48 gold badges413 silver badges533 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
tommy1370
Would you mind taking a look at the new code I posted? I tried to do some more research and think I may have come up with something half-way decent...
Ted Hopp
@tommy1370 - I assume that
token is some sort of global variable. You need to decide whether, on entry to a parse method, token is the first token of the expression expected or whether it is the last token (if any) of what came before. Your method as it stands assumes the former on entry and before calls to parseStatement() and parseExpression(), but leaves token at the semicolon at the end. Presumably the calling method would compensate for that. Also, your method is declared void but you're trying to return a boolean value.lang-java