parsing - Simple "If-Then-Else" descent parser in Java (homework) -
there's no code snippets around web shows how parse ambiguos "if-then-else" grammar (at least pseudo code worth)
in following grammar (upper-case non terminals, quoted terminals , other symbols regular expressions done both terminals , terminals)
stats ::= (stat)* stat ::= if_stat if_stat ::= "if" exp "then" stat ("else" stat)? | exp exp ::= ident ident ::= ('a'-'z''a'-'z')+
the if statement ambiguos infact following code
if if b c else d
can readed both as
if then{ if b c else d }
or
if then{ if b c } else d
now. disambiguating seems simple (given did correctly):
stats ::= (stat)* stat ::= if_stat if_stat ::= "if" exp "then" stat | "if" exp "then" if_stat_ex "else" stat | exp if_stat_ex ::= "if" exp "then" if_stat_ex "else" if_stat_ex | exp exp ::= ident ident ::= ('a'-'z''a'-'z')+
however i'm failing write working parser correctly parse following test cases (each line different test)
//input //expected output if x if y z else w if x (if y z else w) if x y else if z w else k if x y else (if z w else k) if x y else if y w if x y else (if y w ) if x if y z else w else k if x (if y z else w) else k
here's small class reproducing i'm missing.
public class parser{ public list<stat> parsestats(){ list<stat> stats = new list<>(); while(tokenizer.hastokens()) stats.add(parseif()); return stats; } private stat parseif(){ // todo: here? } private exp parsecond(){ exp condition = parseident(); tokenizer.consume( "then" ); return condition; } private exp parseident(){ final ident name = new ident( tokeziner.tostring()); tokenizer.moveonnexttoken(); return name; } }
Comments
Post a Comment