Ejemplo 320
Enunciado
Dada la siguiente gramática, implementar un parser de la misma utilizando la técnica recursiva descendente.
prog ⟶ decl decl
decl ⟶ variables | typedef
variables ⟶ VAR IDENT restoIdents
restoIdents ⟶ ‘,’ IDENT restoIdents
| ‘:’ tipo
tipo ⟶ INT | FLOAT
typedef ⟶ TYPE IDENT restoIdents
Solución
La solución seria:
public class RecursiveParser {
...
public void prog() throws ParseException {
decl();
decl();
match(Lexicon.EOF);
}
void decl() throws ParseException {
if (token.getType() == Lexicon.VAR)
variables();
else if (token.getType() == Lexicon.TYPE)
typedef();
else
error();
}
void variables() throws ParseException {
match(Lexicon.VAR);
match(Lexicon.IDENT);
restoIdents();
}
void restoIdents() throws ParseException {
if (token.getType() == Lexicon.COMA) {
match(Lexicon.COMA);
match(Lexicon.IDENT);
restoIdents();
} else if (token.getType() == Lexicon.PUNTOS) {
match(Lexicon.PUNTOS);
tipo();
} else
error();
}
void tipo() throws ParseException {
if (token.getType() == Lexicon.INT)
match(Lexicon.INT);
else if (token.getType() == Lexicon.FLOAT)
match(Lexicon.FLOAT);
else
error();
}
void typedef() throws ParseException{
match(Lexicon.TYPE);
match(Lexicon.IDENT);
restoIdents();
}
}
Solución
💿 Se puede bajar el proyecto Java con todo lo necesario para poder ejecutar la solución de este ejemplo y así poder ver su resultado.